javascript - 为什么 'this' 在箭头函数中引用时返回 'undefined' 而在匿名函数中调用时却不返回?

标签 javascript node.js javascript-objects arrow-functions

<分区>

我正在使用 node.js v6.7.0 并在声明一个引用“this”的对象时,如果它在箭头函数内则返回未定义,但当它在常规匿名函数内时它返回对象本身(是我想要的)

例如

let obj = {
  key: 'val',
  getScopeWithArrow: () => {return this;}, //returns undefined
  getScopeWithAnonymous: function() {return this;} //returns the object properly
}

最佳答案

因为箭头函数没有自己的 this,所以它们关闭调用上下文的 this。但非箭头函数,如果它们未绑定(bind),则根据它们的调用方式 采用this。我假设您是这样调用这些函数的:

obj.getScopeWithArrow();
obj.getScopeWithAnonymous();

同样,在第一种情况下,箭头函数没有得到它自己的 this,因此您如何调用它并不重要。在第二种情况下,它确实很重要,并且像这样调用它会使调用中的 this 引用 obj 引用的同一对象。


另外:在你的例子中,你必须处于严格模式,因为this在严格模式下只能是undefined

另外 2:关于您的方法名称:this 和“scope”之间的关系非常非常小。


一些例子:

function showThis(label, t) {
  if (t === window) {
    console.log(label, "(global object)");
  } else {
    console.log(label, t);
  }
}
// Loose mode by default in a non-module script element
let obj = {
  arrow: () => {
    showThis("arrow says ", this);
  },
  normal: function() {
    showThis("normal says ", this);
  }
};
obj.arrow();  // global object (window on browsers)
obj.normal(); // obj

function foo() {
  // Here, we're in strict mode
  "use strict";
  let obj = {
    arrow: () => {
      showThis("arrow says ", this);
    },
    normal: function() {
      showThis("normal says ", this);
    }
  };
  obj.arrow();  // undefined
  obj.normal(); // obj

}
foo();

关于javascript - 为什么 'this' 在箭头函数中引用时返回 'undefined' 而在匿名函数中调用时却不返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39987137/

相关文章:

javascript - 如何在 JQuery 中复制/克隆散列/对象?

javascript - 无法读取未定义的属性 'map' - 来自 ReactJS 的错误

javascript - 错误: 3 INVALID_ARGUMENT: Name 'Hello' does not match patterns DialogFlow

node.js - Systemd Node 应用程序无法启动

javascript - 在 Node.js Express 服务器 : res. render(file.ejs, data) 中处理 GET 请求由于未定义数据而无法工作

node.js - 阻塞代码是否总是使用 return 语句,而非阻塞代码总是使用回调?

javascript - 在 JavaScript 中使用正则表达式从字符串中提取 Twitter 处理程序

javascript - 停止 document.ready 函数上的重定向/刷新

JavaScript 从对象数组中获取不在另一个对象数组中的元素

javascript - 从函数访问 javascript 对象