function,new function()和 new Function()

函数是javascrpit中的一等公民,提供了function关键字和Function()这个内置对象。
function和new function()以及new Function()之间的区别一直都会让人造成困扰,下面是一些简单的学习心得。

function

最常用的function用法就是定义函数

var foo = function(){
  			var temp = 100;
  			this.temp = 200;
  			return temp + this.temp ;
  		};

  	 alert(typeof foo);
  	 alert(foo());
  	 
//或者
function foo(){
    var temp = 100;
    this.temp = 200;
    retrun temp + this.temp;
}
// 输出结果都是 function 和300
// 唯一的区别在于后者是函数声明,他的初始化优先级比前者(表达式)要高,无论放在任何位置,都会在同一作用域中第一个表达式被解析前解析。

new function()

其实这并不是一个函数,而是声明一个用户自定义对象,是一个匿名对象。

var foo = new function(){
  	 	var temp = 100;
  	 	this.temp = 200;
  	 	return temp + this.temp;
  	 };
  	 alert(typeof foo);
  	 alert(foo.temp)
  	 alert(foo.constructor());
  	 
 // 输出结果是 Objcect 200 300
 // 因为foo并不是函数,因此不能之间执行

new Function

Function是一个系统内置的函数对象。
使用该方法来声明一个函数。

var foo = new Function('var temp = 100; this.temp = 200; return temp + this.temp;');
alert(typeof foo);
alert(foo());

//在括号中,最后一个逗号前都是该函数的参数,最后一个逗号后面的内容是函数体
//另外这里加不加new 关键字,好像对结果没有任何影响
//ps:这样定义函数的好处和用途目前还没有搞懂,唯一的用途是可以在页面的文本框中定义函数,直接执行。
posted @ 2016-01-11 23:59  刘荘  阅读(528)  评论(0)    收藏  举报