What real purpose does $.noop() serve in jQuery 1.

2020-05-29 12:40发布

Pouring over the release notes regarding jQuery 1.4, I came acrosss $.noop() which is:

Description: An empty function. (added in 1.4)

You can use this empty function when you wish to pass around a function that will do nothing.

Perhaps I'm missing something profound here, but what exactly is a practical use of passing around an empty function?

Code examples appreciated.

9条回答
▲ chillily
2楼-- · 2020-05-29 13:31

The only logical reason is if you're calling a function that does something AND calls another function, and you want the higher-level function to do its thing without calling a parameter function.

Most of the jQuery functions optionally take a parameter function, so you don't have to pass one in. Maybe there's one or two where that's not the case -- or maybe it's to assist developers with their custom code that behaves like this.

查看更多
Luminary・发光体
3楼-- · 2020-05-29 13:33

If you have a function that accepts a function as a parameter, and you don't have any code to give it, you can pass $.noop.

I can't think of any such cases in jQuery where the parameter isn't optional in the first place, though.

Unlike writing function(){}, passing $.noop will not create a new function instance, saving a bit of memory. However, if whatever you're passing it to modifies the function object (eg, funcParam.id = 2), passing $.noop will mess things up.

查看更多
Luminary・发光体
4楼-- · 2020-05-29 13:41

Real World Example (well almost):

jQuery.fn.myAwesomeAjax = function(url, complete) {
  return jQuery.ajax(url || this.url)
    .complete(complete || jQuery.noop);
};

Use it instead of function (){}

查看更多
登录 后发表回答