首页 > 解决方案 > new Function() 如何初始化这个

问题描述

我正在寻找有关使用new Function()构造函数时如何初始化this值的信息。

我已经在节点 10.24.0 上对其进行了测试,它的行为看起来与 lambas(arrow functions) 的行为相同:没有设置,因为没有构建闭包。

我的猜测正确吗?

这是简单的测试:

> let o = { 'a' : 1, f : new Function('return this;') };
> o;
{ a: 1, f: [Function: anonymous] }
> o.f();
{ a: 1, f: [Function: anonymous] }

标签: javascriptfunctionconstructor

解决方案


显然,这是不正确的,正如您自己的测试所证实的那样。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


推荐阅读