开发者

why this way "this.foo = new (function () {..})();" vs. "this.foo = function (){...};"

Is there any differe开发者_如何转开发nce in the two definitions and assignments of functions?

this.foo = new (function () {..})();

vs.

this.foo = function (){...};


In the first example, it's creating a function and executing it, assigning the result to this.foo. In the second example, it's creating the function and assigning the function itself to this.foo.


The main difference is calling the function with a "new" and assigning the anonymous function to a variable

ECMA 262 15.3.2: When Function is called as part of a new expression, it is a constructor: it initialises the newly created object.

So this.foo = new (function () {..})(); creates a new object and assigns it to this.foo

and

this.foo = function (){...}; defines an anonymous function and assigns it to this.foo

also another way is this.foo = (function () {..})(); (without the "new") will call the function and assign its return value to this.foo

In your case if you alert:

var foo = new (function () {})();
var bar = function() {};
var baz = (function () {return "boo";})(); // without the "new"

alert(foo); // will alert [object Object], the newly created object
alert(bar); // will alert function) {}, the function itself
alert(baz); // will alert "boo", the functions return value


Your first example is plain wrong, have you actually tried it? If you want to use new and the Function constructor it works like this:

foo = new Function("function body");

(This is the worst possible way of defining a function)

Example 2 is the way to go.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜