difference between Function and new Function

北城余情 提交于 2019-12-04 01:19:04

问题


I sometimes see people doing this Function('alert("hi")') and sometimes they do new Function('alert("hi")')

Is there a difference between the two?


回答1:


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 cinstructor at all costs.
It needs to eval the string you pass to it; eval is evil, and slow too.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/4832096/difference-between-function-and-new-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!