JS里的function与new function

javascript里 经常看到
例子:
document.body.onload=function(xxx)
document.body.onload=new function(xxx)
document.body.onload=function(){xxxxxxxxx}
小的我 还没明白 他有什么区别呢? 希望各位 讲解一下

下面也是例子
1
var foo01 = function() {
var temp = 100;
this.temp = 200;
return temp + this.temp;
}

2
var foo02 = new function()
{
var temp = 100;
this.temp = 200;
return temp + this.temp;
}

3
var foo3 = new Function(’var temp = 100; this.temp = 200; return temp + this.temp;’);

document.body.onload=function(xxx)
document.body.onload=new function(xxx)
document.body.onload=function(){xxxxxxxxx}
首先第一种:
楼主不要写成function(xxx),否则大家都以为是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;’);
在上面已经提及过了。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-03-22
就是定义函数嘛
最普通的function使用方式,定一个JavaScript函数。在大扩号内的变量作用域中,this指代foo01的所有者,即window对象。

new function使用系统内置函数对象来构建一个函数,就是函数体以字符串形式给出。
2、这个用法和函数本身的使用基本没有任何关系,在大扩号中会构建一个变量作用域,this指代这个作用域本身。

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网