new function(){},Function,new Function()区别

函数是JavaScript中很重要的一个语言元素,并且提供了一个[color=red]function关键字和内置对象Function[/color],下面是用法和它们之间区别。

使用方法一:
var foo01 = function() //or fun01 = function()
{
var temp = 100;
this.temp = 200;
return temp + this.temp;
}

alert(typeof(foo01));
alert(foo01());

运行结果:
function
300
最普通的function使用方式,定一个JavaScript函数。两种写法表现出来的运行效果完全相同,唯一的区别是后一种写法有较高的初始化优先级。在大扩号内的变量作用域中,this指代foo01的所有者,即window对象。

使用方法二:
var foo02 = new function()
{
var temp = 100;
this.temp = 200;
return temp + this.temp;
}

alert(typeof(foo02));
alert(foo02.constructor());

运行结果:
object
300
这是一个比较puzzle的function的使用方式,好像是定一个函数。但是实际上这是定一个[color=red]JavaScript中的用户自定义对象[/color],不过这里是个匿名类。这个用法和函数本身的使用基本没有任何关系,在大扩号中会构建一个变量作用域,this指代这个作用域本身。
var obj = (new function(){
this.a = 123;
this.fn = function(e){alert(e)};
//return new String('123');
//return 123;
});
obj.fn(123);
可以理解返回一个对象。
(new function(){
return '123';
})

(new function(){
return new String('123');
}) 又有什么区别呐?


使用方法三:
var foo3 = new Function('var temp = 100; this.temp = 200; return temp + this.temp;');
alert(typeof(foo3));
alert(foo3());

运行结果:
function
300
使用系统内置函数对象来构建一个函数,这和方法一中的第一种方式在效果和初始化优先级上都完全相同,就是函数体以字符串形式给出。

使用方法四:
var foo4 = Function('var temp = 100; this.temp = 200; return temp + this.temp;');
alert(typeof(foo4));
alert(foo4());

运行结果:
function
300

参考:

[url]http://www.jb51.net/article/13894.htm[/url]
[url]http://www.jb51.net/article/13895.htm[/url]
[url]http://www.planabc.net/2008/02/20/javascript_new_function/[/url]
[url]http://cykit.iteye.com/blog/72950[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值