在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方法?
首先,我创建一个ES5函数,然后创建它的原型:
var Person = function() {};
Person.prototype.city = function() {return 'New York'}Run Code Online (Sandbox Code Playgroud)
我在这里没有错误.但是当我用ES6胖箭头功能创建相同的时候,我得到Cannot set property 'city' of undefined:
let Person = () => {};
Person.prototype.city = () => {return 'New York'}Run Code Online (Sandbox Code Playgroud)
为什么是这样?