const profile = {
name: 'Alex',
getName:() => this
};
console.log(profile.getName());
我想问为什么结果是窗口而不是配置文件对象?箭头功能,这在我的代码
const profile = {
name: 'Alex',
getName:() => this
};
console.log(profile.getName());
我想问为什么结果是窗口而不是配置文件对象?箭头功能,这在我的代码
因为您已经使用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());
下一次,将一个明显的副本作为副本关闭... – Cerbrus
所以基本上,你是不是familair带箭头的功能和常规功能之间的差异。
new
使用,这意味着它们不具有prototype
属性,并且不能被用于创建一个类状方式的对象。arguments
属性。 (但是,您可以在ES6,使用splats
模仿相同的行为:(...args) => { console.log(args) }
new.target
财产,他们用自己的封闭功能的new.target
,如果它存在this
值他们没有一个,this
中搜索的词汇范围,这允许重提this
外的范围,通常是在回调中非常有用结论: 在全球范围内定义您的变量,this
将参考window
,因为它与全球范围相同:)(差异#4适用于此处)
huibin,请在对SO提出问题之前做一些研究。 “这个”具体主题已经被多次回答了。 – Cerbrus