最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - why this way "this.foo = new (function () {..})();" vs. "this.foo = function (){...};&am

programmeradmin3浏览0评论

Is there any difference in the two definitions and assignments of functions?

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

vs.

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

Is there any difference in the two definitions and assignments of functions?

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

vs.

this.foo = function (){...};
Share asked Aug 16, 2010 at 16:21 XerionXerion 3,2815 gold badges31 silver badges47 bronze badges 1
  • See also: stackoverflow./questions/2274695/… and stackoverflow./questions/1895635/… – Christian C. Salvadó Commented Aug 16, 2010 at 16:43
Add a ment  | 

3 Answers 3

Reset to default 8

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)

  1. 暂无评论