简体   繁体   English

foo()和function()之间的区别{foo(); }

[英]Difference between foo() and function() { foo(); }

Is there any advantage of wrapping a function with an anonymous function? 使用匿名函数包装函数有什么好处吗? I mean a particular example: 我的意思是一个特例:

function asyncFuntion(callback) {
    setTimeout(callback, 6000);
};

asyncFuntion(function() {
    console.log('Calling after 6 s.');
});   

and with the wrapped function: 以及包装功能:

function asyncFuntion(callback) {
    setTimeout(function() {
        callback();
    }, 6000);
};

asyncFuntion(function() {
    console.log('Calling after 6 s.');
});

In both cases output is the same. 在这两种情况下输出都是相同的。 So is there any difference? 那有什么区别吗? The second version is what I found learning js. 第二个版本是我发现的学习js。 I realize that such a form is useful when we need closures but here? 我知道当我们需要闭包时这样的表格很有用但是在这里?

The second form allows you to pass arguments to callback , whereas the first form doesn't. 第二种形式允许您将参数传递给callback ,而第一种形式则不允许。

// 1st form
setTimeout(callback("This doesn't work as you might expect"), 6000);

// 2nd form
setTimeout(function() {
    callback("This works");
}, 6000);

If you're not passing arguments, then there is no advantage in wrapping the function whatsoever. 如果你没有传递参数,那么包装函数没有任何优势。


To be more thorough, Function.prototype.bind can help us with the first form: 为了更加彻底, Function.prototype.bind可以帮助我们使用第一种形式:

 setTimeout(callback.bind(this, "This works fine too"), 6000); // Even with Richard JP Le Guen's example by specifying the thisObj setTimeout(customObj.alert.bind(customObj), 6000); 

However, you will need to provide this method to browsers that don't support the event (namely Opera, Safari and IE 8, 7, 6). 但是,您需要将此方法提供给不支持该事件的浏览器(即Opera,Safari和IE 8,7,6)。 The code to shim the method is available on the MDN documentation page. 可以在MDN文档页面上找到用于填充方法的代码。

Wrapping a function in an anonymous function can avoid complications with the this keyword. 在匿名函数中包装函数可以避免使用this关键字的复杂性。 ( read about them on quirksmode ) 在quirksmode上阅读它们

For example: 例如:

function CustomObject() {
    this.msg = "Hello world from my custom object";
    this.alert = function() {
        alert(this.msg);
    };
}

var customObj = new CustomObject();

setTimeout(customObj.alert, 1000); // the alert message says `undefined`
setTimeout(function() {
    customObj.alert();
}, 2000); // the alert message says "Hello world from my custom object"

Wrapping a function in an anonymous function is also key to using closures in JavaScript: 在匿名函数中包装函数也是在JavaScript中使用闭包的关键:

var arr = ['a','b','c','d','e'];

// will always alert undefined
for(var i=0; i<arr.length; i++) {
    setTimeout(function() {
        console.log(arr[i]);
    }, 1000*i);
}

// outputs the values of `arr`
for(var j=0; j<arr.length; j++) {
    setTimeout((function(indx) {
        return function() {
            console.log(arr[indx]);
        }
    }(j)), 1000*j);
}

Wrapping is useful if you need to have separate identity. 如果您需要具有单独的标识,则环绕非常有用。

var x = function () { cleanup(); };
var y = function () { cleanup(); };
if (x === y) ... // not true

For example, some functions like addEventListener operate on identity. 例如,某些函数(如addEventListener对identity进行操作。

element.addEventListener("myEvent", beep, false);
element.addEventListener("myEvent", beep, false);

The second time you call addEventListener , it says "I've already got a beep ; I don't need to add another." 第二次调用addEventListener ,它说“我已经beepbeep ;我不需要添加另一个。” When the myEvent event is fired, you get only one beep. 触发myEvent事件时,只会发出一声嘟嘟声。 If you want two beeps, you need to make sure the callbacks are different. 如果您想要发出两声嘟嘟声,则需要确保回调不同。

element.addEventListener("myEvent", function() { beep(); }, false);
element.addEventListener("myEvent", function() { beep(); }, false);

Each anonymous function is different, so this time you registered two functions (which happen to do the same thing). 每个匿名函数都不同,所以这次你注册了两个函数(碰巧做同样的事情)。 Now it will beep twice. 现在它会发出两声哔哔声。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 foo(),foo和function(){foo()}之间的js区别 - js difference between foo(), foo and function(){foo()} JavaScript中a ==&#39;foo&#39;和&#39;foo&#39;== a之间的区别 - Difference between a == 'foo' and 'foo' == a in javascript Javascript 中的 function foo(){} 和 foo: function(){} 有什么区别? - What is the difference between function foo(){} and foo: function(){} in Javascript? var foo = function(){...}()和var foo =(function(){...}())之间的区别 - Difference between var foo = function(){…}() and var foo = (function(){…}()) if(x){foo(); 和x? foo():0; - Difference between if (x) { foo(); } and x ? foo() : 0; &#39;function foo(callback)&#39;和&#39;foo(arg1,arg2,function(err,data))&#39;之间有什么区别? - What's the difference between 'function foo (callback)' and 'foo(arg1, arg2, function(err,data))'? `when(foo,f)`和`when(foo).then(f)`有什么区别 - What is the difference between `when(foo, f)` and `when(foo).then(f)` js中“foo.bar”和“foo [&#39;bar&#39;]”之间的区别 - Difference between “foo.bar” and “foo['bar']” in js 快递路线中`/:foo *`和`/:foo(。*)`有什么区别? - What's the difference between `/:foo*` and `/:foo(.*)` in express routes? foo.join和foo.resolve之间的区别? 在webpack中 - Difference between foo.join and foo.resolve? In webpack
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM