fox*_*fox 70 javascript ecmascript-harmony ecmascript-6
在ES6中,这两个都是合法的:
var chopper = {
owner: 'Zed',
getOwner: function() { return this.owner; }
};
Run Code Online (Sandbox Code Playgroud)
并且,作为速记:
var chopper = {
owner: 'Zed',
getOwner() { return this.owner; }
}
Run Code Online (Sandbox Code Playgroud)
是否可以使用新的箭头功能?在尝试类似的东西
var chopper = {
owner: 'John',
getOwner: () => { return this.owner; }
};
Run Code Online (Sandbox Code Playgroud)
要么
var chopper = {
owner: 'John',
getOwner: () => (this.owner)
};
Run Code Online (Sandbox Code Playgroud)
我收到一条错误消息,提示该方法无权访问this.这只是一个语法问题,还是你不能在ES6对象中使用fat-pipe方法?
小智 114
箭头功能并非设计用于各种情况,仅仅作为旧式功能的较短版本.它们无意使用function关键字替换函数语法.箭头函数最常见的用例是短的"lambdas",它不重新定义this,通常在将函数作为回调传递给某个函数时使用.
箭头函数不能用于编写对象方法,因为正如您所发现的那样,由于箭头函数靠近this词法封闭上下文,this因此箭头内的是当前定义对象的位置.这就是说:
// Whatever `this` is here...
var chopper = {
owner: 'Zed',
getOwner: () => {
return this.owner; // ...is what `this` is here.
}
};
Run Code Online (Sandbox Code Playgroud)
在您的情况下,想要在对象上编写方法,您应该只使用传统function语法或ES6中引入的方法语法:
var chopper = {
owner: 'Zed',
getOwner: function() {
return this.owner;
}
};
// or
var chopper = {
owner: 'Zed',
getOwner() {
return this.owner;
}
};
Run Code Online (Sandbox Code Playgroud)
(它们之间有微小差异,但如果你用他们唯一重要super的getOwner,你都没有,或者如果你复制getOwner到另一个对象.)
在es6邮件列表上有一些关于箭头函数扭曲的争论,这些函数具有相似的语法但有自己的this.但是,这个提议很难被接受,因为这仅仅是语法糖,允许人们保存键入几个字符,并且不提供现有函数语法的新功能.请参阅未绑定箭头功能主题.
在这一行getOwner: => (this.owner)应该是:
var chopper = {
owner: 'John',
getOwner: () => this.owner
}; //here `this` refers to `window` object.
Run Code Online (Sandbox Code Playgroud)
你必须声明this一个函数:
var chopper = {
owner: 'John',
getOwner() { return this.owner }
};
Run Code Online (Sandbox Code Playgroud)
要么:
var chopperFn = function(){
this.setOwner = (name) => this.owner = name;
Object.assign(this,{
owner: 'Jhon',
getOwner: () => this.owner,
})
}
var chopper = new chopperFn();
console.log(chopper.getOwner());
chopper.setOwner('Spiderman');
console.log(chopper.getOwner());Run Code Online (Sandbox Code Playgroud)
如果必须使用箭头功能,可以this改为chopper,
var chopper = {
owner: "John",
getOwner: () => chopper.owner
};
Run Code Online (Sandbox Code Playgroud)
尽管这不是最佳实践,但是当您更改对象名称时,您必须更改此箭头功能。