<分区>
我在this site中找到了以下代码(不包括 console.log
内容):
console.log((function(x, f = () => x) {
var x;
// console.log(this.x,x); // undefined 1
var y = x;
x = 2;
return [x, y, f()];
})(1)); // [2, 1, 1]
显然 f()
与 x
具有相同的结果,后者在参数中传递。如果您取消注释 console.log(this.x,x)
,它将显示 undefined 和 1。
我已阅读以下内容:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
What is the difference between () => {} and function() {} in react-native javascript?
What does this refer to in a JavaScript function?
How does the "this" keyword work?
我的问题是,即使您设置了 var x = 2
,为什么 this.x
仍会返回 undefined?请引用以下片段:
console.log((function(x, f = () => x) {
var x = 2;
console.log(this.x,x); // undefined 2
var y = x;
x = 2;
return [x, y, f()];
})(1)); // [2, 2, 1]
如果你删除 var x
console.log((function(x, f = () => x) {
console.log(this.x,x); // undefined 1
var y = x;
x = 2;
return [x, y, f()];
})(1)); // [2, 1, 2]
this.x
不指向参数或局部变量吗?