Arrow functions are not designed to be used in every situation merely as a shorter version of old-fashioned functions. They are not intended to replace function syntax using the function
keyword. The most common use case for arrow functions is as short "lambdas" which do not redefine this
, often used when passing a function as a callback to some function.
Arrow functions cannot be used to write object methods because, as you have found, since arrow functions close over the this
of the lexically enclosing context, the this
within the arrow is the one that was current where you defined the object. Which is to say:
// Whatever `this` is here...
var chopper = {
owner: 'Zed',
getOwner: () => {
return this.owner; // ...is what `this` is here.
}
};
In your case, wanting to write a method on an object, you should simply use traditional function
syntax, or the method syntax introduced in ES6:
var chopper = {
owner: 'Zed',
getOwner: function() {
return this.owner;
}
};
// or
var chopper = {
owner: 'Zed',
getOwner() {
return this.owner;
}
};
(There are small differences between them, but they're only important if you use super
in getOwner
, which you aren't, or if you copy getOwner
to another object.)
There was some debate on the es6 mailing list about a twist on arrow functions which have similar syntax but with their own this
. However, this proposal was poorly received because that is mere syntax sugar, allowing people to save typing a few characters, and provides no new functionality over existing function syntax. See the topic unbound arrow functions.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…