javascript - 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] }
解决方案
显然,这是不正确的,正如您自己的测试所证实的那样。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
推荐阅读
- python - 为什么 sklearn 随机森林需要相同的时间来预测一个样本而不是 n 个样本
- android - Android minifyEnabled true for firebase
- search - PixelSearch 偶尔找不到 PixelGetColor 找到的颜色
- python - 如何按子列表的第一项然后按第三项对列表列表进行排序
- sharepoint - Sharepoint 在线:以编程方式发布到新闻源
- python - 在 Python 中读取 RTF - PyRTF
- google-sheets - 方法电子表格.batchUpdate 不适用于 API 密钥
- python - Python:比较 CSV 文件并保存与第一行的差异(列名)
- javascript - 输入框不接受任何 ReactJS
- spring - com.code.service.BookServiceImpl 中的字段 bookRepository 需要找不到类型为“com.myAppp.code.respository.BookRepository”的 bean