function,new function()和 new Function()

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

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是一个系统内置的函数对象。
使用该方法来声明一个函数。this

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

//在括号中,最后一个逗号前都是该函数的参数,最后一个逗号后面的内容是函数体
//另外这里加不加new 关键字,好像对结果没有任何影响
//ps:这样定义函数的好处和用途目前尚未搞懂,惟一的用途是能够在页面的文本框中定义函数,直接执行。
相关文章
相关标签/搜索