为什么“this”指的是对象“obj”而不是全局对象

Why does 'this' refer to the object 'obj' not global object

本文关键字:对象 全局 obj this 为什么      更新时间:2023-09-26
var obj = {
  name: 'hello',
  getName: function(){
  return () => {return this.name; }
  }
}
var name = 'world';
var nameFunc = obj.getName();
console.log(nameFunc())

结果是"你好",而不是"世界"。我有点困惑。

箭头函数"诞生"绑定到this的值,就像它们创建时一样。当您拨打getName()电话时:

var nameFunc = obj.getName();

那么在getName()里面,this的值是对obj的引用。 您的 return 语句构造箭头函数,因此该函数绑定到 obj 。就好像你写了:

  getName: function() {
    return function() {
      return this.name;
    }.bind(this);
  }

这只是箭头函数的工作方式,是的,它与常规函数不同。