javascript - typeof Function.prototype 是 function 为什么不可以当作构造函数
阿神
阿神 2017-04-11 11:22:29
[JavaScript讨论组]

typeof Function.prototype 是 function 为什么不可以当作构造函数 与前者有什么

阿神
阿神

闭关修行中......

全部回复(1)
天蓬老师

是可以当做构造函数来用的

var adder = new Function('a', 'b', 'return a + b');

// Call the function
adder(2, 6);
// > 8

区别的话,用构造函数生成的函数不会有闭包,他们只能访问自身作用域和全局作用域声明的变量和函数。其他详细的地方参考MDN

Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called. This is different from using eval with code for a function expression.

var x = 10;

function createFunction1() {
    var x = 20;
    return new Function("return x;"); // this |x| refers global |x|
}

function createFunction2() {
    var x = 20;
    function f() {
        return x; // this |x| refers local |x| above
    }
    return f;
}

var f1 = createFunction1();
console.log(f1());          // 10
var f2 = createFunction2();
console.log(f2());          // 20
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号