开发者

difference between Function and new Function

I sometimes see people doing this Function('alert("hi")') and sometimes th开发者_Go百科ey do new Function('alert("hi")')

Is there a difference between the two?


The spec (page 127) says they're identical.

15.3.1.1 Function (p1, p2, … , pn, body)

When the Function function is called with some arguments p1, p2, … , pn, body (where n might be 0, that is, there are no “p” arguments, and where body might also not be provided), the following steps are taken:

  1. Create and return a new Function object as if the standard built-in constructor Function was used in a new expression with the same arguments (15.3.2.1).

However, you should avoid the Function constructor at all costs.
It needs to eval the string you pass to it; eval is evil, and slow too.


There is only one usage of new Function. It is this:

var constructor = new Function;

// then this 

constructor.prototype = { 
    //...  stuff
};

// OR

constructor.prototype = new someOtherThing;

// then

var obj = new constructor;

Basically you can use new Function if you want to create an object constructor with an empty constructor that only uses inheritance.

If you want a function to do anything then don't use Function at all.


To answer your question: Function(...) and new Function(...) are exactly the same according to the ECMA5 specs.

To shed some light as to when and where this should be used, the answer is rarely. I know of one situation where we have used Function(...), and it was when creating custom ASP.NET server controls. We often have something to the effect of [ServerControl].OnClientClick, which specifies a JavaScript string (on the server side) that should be ran on the client side when the click event occurs. We then put the JS string into a Function and call it when specific conditions have been met. This also allows us to invoke the .call(...) function to set the context and to pass in the event parameters as if the JS were being called from an onclick attribute.


Invoking the Function constructor as a function (without using new operator) has the same same effect as invoking it as constructor.

That means it is same to code if you do it:

var result1 = new Function('a', 'b', 'return a + b')
var result2 = Function('a', 'b', 'return a + b')

result1 and result2 are same.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜