坏小仔

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

All functions in JavaScript are an instance of Function.; we learned that back in chapter 3.
There we saw how we could create named functions using syntax such as function
name(...){...}, or omit the name to create anonymous functions.
However, we can also instantiate functions directly using the Function constructor, as
shown in the following code:
var add = new Function("a", "b", "return a + b;");
assert(add(3,4) === 7, "Function created and working!");


The last argument of a variable argument list to the Function constructor is always the
code that will become the body of the function. Any preceding arguments represent the
names of the parameters for the function.
So our example is equivalent to:
var add = function(a,b) { return a + b; }


While these are functionally equivalent, a glaring difference is that in the Function
constructor approach, the function body is provided by a run-time string.
Another difference that’s vitally important to realize is that no closures are created when
functions are created via the Function constrictor. This can be a good thing when we don't
want to incur any of the overhead associated with unneeded closures.

posted on 2012-08-22 17:00  坏小仔  阅读(105)  评论(0编辑  收藏  举报