怎么理解function 与 new Function 在函数 作用域链上的区别呢?

怎么理解function 与 new Function 在函数 作用域链上的区别呢?

请看下面的代码,然后解释一下 运行结果的差异,谢谢!

代码1: 运行结果 10
function f1()
{
var t1 = 10;
return function(){alert(t1);};
}
var t1 = 5;
f1()();

代码2: 运行结果 5
function f1()
{
var t1 = 10;
return new Function('alert(t1);');
}
var t1 = 5;
f1()();

代码3:运行结果 5
function f2(a1)
{
var t1 = 10;
a1(t1);
}
var t1 = 5;
var f1 = function(){alert(t1);};
f2(f1);

代码4:运行结果 5
function f2(a1)
{
var t1 = 10;
a1(t1);
}
var t1 = 5;
var f1 = new Function('alert(t1);');
f2(f1);
[b]问题补充:[/b]
to lovewhzlq :

仔细看了你发的两个帖子,其中,在第2个帖子中《理解 JavaScript 闭包》,终于找到了 function 和 new Function在变量作用域链上存在差别的原因,文中是这样说的:

“通过调用 Function 构造函数创建的函数对象,其内部的 [[scope]] 属性引用的作用域链中始终只包含全局对象。

通过函数声明或函数表达式创建的函数对象,其内部的 [[scope]] 属性引用的则是创建它们的执行环境的作用域链。”

这就解释了上面 第1、2段代码为何结果有差异,
而第3、4段代码为何结果相同的原因。

再次感谢!!

这个涉及到闭包的问题了,

看些不错的文章就理解了

http://www.cn-cuckoo.com/2007/08/01/understand-javascript-closures-72.html
http://www.v-ec.com/dh20156/article.asp?id=87

document.body.onload=function(xxx)
document.body.onload=new function(xxx)
document.body.onload=function(){xxxxxxxxx}
首先第一种:
function关键字,其实只是个自定义的函数。

至于下面这种写法效果是一样的,但是注意了这里有new关键字,而且不是function,而是Function,比如说:
document.onmouseup=new Function("flag=true");

第三种即最常见的一种,语法为:
function(){statement}


一.
var foo01 = function() {
var temp = 100;
this.temp = 200;
return temp + this.temp;
}
这里重载了foo01函数,效果和function foo01(){statement}差不多,但是区别在于var foo01=function(){statement}重装了foo01函数,也就相当于个模型,区别还是有的,比如说有个函数分别调用了这两种方式写的函数foo01,但是例子中的写法将foo01的方法继承了,但是function foo01(){}这种写法则直接执行了函数,所以两个写法都很有用处。

二.
var foo02 = new function()
{
var temp = 100;
this.temp = 200;
return temp + this.temp;
}
这种写法不常见,但是它和例一差不多,只不过多了关键字new,很明显该函数必须先定义自定义函数的模型,然后才能对此函数用new关键字来实例化。

三.
var foo3 = new Function(’var temp = 100; this.temp = 200; return temp + this.temp;’);
在上面已经提及过了。