【发布时间】:2025-12-07 13:05:02
【问题描述】:
我正在尝试在各种情况下设置this。
node.js 中执行的以下代码v6.8.1 将打印每行末尾的注释内容:
function requireFromString(src) {
var Module = module.constructor;
var m = new Module();
m._compile(src, __filename);
return m.exports;
}
(function(){
var f1 = (() => {console.log(this.a === 1)});
var f2 = function(){ console.log(this.a === 1) };
var f3 = requireFromString('module.exports = (() => {console.log(this.a === 1)});');
var f4 = requireFromString('module.exports = function(){ console.log(this.a === 1) };');
console.log('Body:');
console.log(this.a === 1); // true
(()=>console.log(this.a === 1))(); // true
(()=>console.log(this.a === 1)).call(this); // true
(function(){console.log(this.a === 1)})(); // false
(function(){console.log(this.a === 1)}).call(this); // true
console.log('\nFunctions:');
f1(); // true
f1.call(this); // true
f2(); // false
f2.call(this); // true
f3(); // false [1]
f3.call(this); // false [2]
f4(); // false
f4.call(this); // true
}).apply({a:1});
有了this 和arrow functions 的文档,我可以解释所有情况,除了标有[1] 和[2] 的情况。
有人可以阐明观察到的行为吗?也许给我一个提示我如何调用f3 以便函数打印为真。
备注
-
requireFromString-function 改编自 Load node.js module from string in memory,它只是简化这个 * 问题的一个技巧。在实践中,这被普通的require(...)取代
【问题讨论】:
-
箭头函数的重点是从词法上下文中继承
this的值。如果那不是你想要的,那么不要使用箭头函数。如果要“设置”或“控制”this的值,请使用常规函数调用和可用的各种方法之一(.apply()、.call()、obj.method()等...)在该函数调用中控制this的值。 -
您在调用
f4();和f4.call(this);时是否有预期的行为? -
给你一些背景信息:我正在重构FluentFlow,它使用用户提供的函数,即所谓的“匹配器”。作为detecting arrow functions seems to be hard(我不喜欢接受的答案),无论提供什么样的功能,我都想为“匹配器”设置
this。 -
更多上下文:this is how a matcher should be defiend by the user 和 this is how the matcher is called by FluentFlow,是的:我知道我可以简单地将 obj 作为参数传递。但我确实喜欢
this版本的可读性。
标签: javascript node.js arrow-functions