javascript - 函数返回未定义中的 this.variable 有什么问题

标签 javascript ecmascript-6

<分区>

我在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 are the differences (if any) between ES6 arrow functions and functions bound with Function.prototype.bind?

What does this refer to in a JavaScript function?

How does the "this" keyword work?

this - JavaScript | MDN

我的问题是,即使您设置了 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 不指向参数或局部变量吗?

最佳答案

摘自 Kyle Simpson 的书 You don't know JS

this is actually a binding that is made when a function is invoked, and what it references is determined entirely by the call-site where the function is called.

如果你想弄清楚 this 指的是什么,有 4 个规则要遵循

  1. 调用新的?使用新构造的对象。

  2. 通过 call 或 apply(或 bind)调用?使用指定对象。

  3. 使用拥有调用的上下文对象调用?使用该上下文对象。

  4. 默认值:在严格模式下未定义,否则为全局对象。

这里,this 指的是全局对象,所以this.x 是未定义的。 如果你想强制执行它,你可以使用bind

如果您想了解更多有关所有技术细节的信息,您应该阅读 this

关于javascript - 函数返回未定义中的 this.variable 有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55586395/

相关文章:

javascript - 从 Javascript 访问在服务器端创建的 Cookie

javascript - ES6 + SystemJs - 为什么我必须使用 .js 扩展名来导入 es6 模块?

javascript - "MultiplicativeExpression"是什么意思?

javascript - 在meteor中添加外部脚本并使用es6导入控制它们的加载顺序

javascript - 要求失败时的常量行为

javascript - ES2015+ 有效地将对象数组转换为以对象数组作为值的分组 HashMap 的方法

java - 使用浏览器访问文件系统文件

javascript - Select2 自定义读取自定义数据属性

javascript - 验证字符串格式

javascript - 突出显示菜单上的事件链接