我已阅读 Function 。所以我尝试通过new Function将函数声明转换为函数表达式。但是,我被困在下面的代码中:
function Foo(name, age) {
Foo.prototype.name = name;
Foo.prototype.age = age;
}
var foo = new Foo(1,2); // this is ok
console.log(Foo.prototype.hasOwnProperty('name'));
console.log(foo.hasOwnProperty('name'));
但是转换后出现错误:
var Foo = new Function(['name', 'age'], 'Foo.prototype.name=name;Foo.prototype.age=age;');
var foo = new Foo(1,2); // error: Foo is not defined
console.log(Foo.prototype.hasOwnProperty('name'));
console.log(foo.hasOwnProperty('name'));
有什么错误吗?任何答案都有帮助。
代码就在我的 Chrome 浏览器中。但是它在平台上出错:
- nodejs:6.10.0
- win7 64位
最佳答案
该错误是因为 var Foo
未定义在 Function
可以访问的位置,至少在使用 Node 时没有。
当您使用 new Function()
构造函数从字符串创建函数时,该函数只能访问全局范围,无论它是在哪里创建的。
而且,在 Node 模块中,var Foo
和 var foo
不是全局变量。它们是局部变量,仅存在于当前文件/模块中的“模块”范围内。
var bar = 'bar';
console.log(bar); // function
console.log(global.bar); // undefined
要允许 new Function()
访问 Foo
,您必须将后者定义为全局变量(或 global 的属性)
对象)。
global.Foo = new Function(['name', 'age'], 'Foo.prototype.name=name;Foo.prototype.age=age;');
var foo = new Foo(1,2);
// ...
<小时/>Though, you should be aware that modifying the global scope/object like this is generally frowned upon in Node, since this goes against its intent/design of using isolated modules.
不过,要从表达式定义函数,您不需要使用 Function
构造函数。您可以改为 place the declaration where an Expression is expected ,例如在赋值运算符之后。
var Foo = function (name, age) {
Foo.prototype.name = name;
Foo.prototype.age = age;
};
var foo = new Foo(1,2); // this is ok
// ...
关于javascript - 新功能有错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42743075/