方法在ES6对象中:使用箭头函数在ES6中,这两项法律都是合法的:var chopper = {
owner: 'Zed',
getOwner: function() { return this.owner; }};而且,作为速记:var chopper = {
owner: 'Zed',
getOwner() { return this.owner; }}是否也可以使用新的箭头函数?在尝试类似的var chopper = {
owner: 'John',
getOwner: () => { return this.owner; }};或var chopper = {
owner: 'John',
getOwner: () => (this.owner)};我收到一条错误消息,提示该方法无法访问this。这只是语法问题,还是不能在ES6对象中使用FAT管道方法?
3 回答
紫衣仙女
TA贡献1839条经验 获得超15个赞
在这一行getOwner: => (this.owner)应:
var chopper = {
owner: 'John',
getOwner: () => this.owner
}; //here `this` refers to `window` object.
你必须声明this变成一种功能:
var chopper = {
owner: 'John',
getOwner() { return this.owner }
};
或:
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());
添加回答
举报
0/150
提交
取消