2017-09-28 73 views
-3
const profile = { 
    name: 'Alex', 
    getName:() => this 

}; 

console.log(profile.getName()); 

我想问为什么结果是窗口而不是配置文件对象?箭头功能,这在我的代码

+1

huibin,请在对SO提出问题之前做一些研究。 “这个”具体主题已经被多次回答了。 – Cerbrus

回答

7

因为您已经使用arrow function。箭头函数将保留外部this,这意味着this中的箭头函数指的是外部的this,它们在您的情况下是全局对象:window。将其替换为function以保留this以引用当前对象。

const profile = { 
 
    name: 'Alex', 
 
    getName: function() { return this; } 
 
}; 
 

 
console.log(profile.getName());

您可以检查此

const profile = { 
 
    isThisPreserved:() => this === window 
 
}; 
 

 
console.log(profile.isThisPreserved());

+2

下一次,将一个明显的副本作为副本关闭... – Cerbrus

1

所以基本上,你是不是familair带箭头的功能和常规功能之间的差异。

  1. 箭功能不能与new使用,这意味着它们不具有prototype属性,并且不能被用于创建一个类状方式的对象。
  2. 箭头函数无权访问通常存在于普通函数中的arguments属性。 (但是,您可以在ES6,使用splats模仿相同的行为:(...args) => { console.log(args) }
  3. 箭函数没有自己的new.target财产,他们用自己的封闭功能的new.target,如果它存在
  4. 箭功能别。 :T绑定this值他们没有一个,this中搜索的词汇范围,这允许重提this外的范围,通常是在回调中非常有用

结论: 在全球范围内定义您的变量,this将参考window,因为它与全球范围相同:)(差异#4适用于此处)