我正在寻找如何在使用new Function()构造函数时初始化this的值的信息。
我已经在节点10.24.0上测试了它,看起来行为与lambas(箭头函数)相同:没有这个被设置,因为没有构建闭包。
我猜对了吗?
下面是一个简单的测试:
> let o = { 'a' : 1, f : new Function('return this;') };
> o;
{ a: 1, f: [Function: anonymous] }
> o.f();
{ a: 1, f: [Function: anonymous] }
显然,这是不正确的,正如您自己的测试所证实的那样。Function()
创建的是一个普通函数,而不是一个箭头,因此在创建时没有发生this
绑定。
let o = {
'a' : 1,
x: function() { return this },
y : new Function('return this;'),
z: () => { return this }
};
console.log(o.x() === o) // yes
console.log(o.y() === o) // yes
console.log(o.z() === window) // yes