This (property initialization with a function expression):
let username = {
age: function() {
}
};
and this (method syntax):
let username = {
age() {
}
};
do slightly different things, but often you don't care about the difference.
There are a couple of differences between a property initializer using a function and method syntax:
- With method syntax, the code within the method can use the
super
keyword to access things on its prototype object. When doing a property with a function expression initializer, it can't. Method syntax enables super
by attaching the object you created the method on to the method as an internal field called [[HomeObject]] in the spec (you can't access internal fields); then super.x
looks up the current prototype of the [[HomeObject]] and accesses x
on it.
- With method syntax, the resulting function is just a function/method, not a constructor function. With the first code block above, you could do
new username.age()
and create an object; with the second, you couldn't. (And since they aren't constructor functions, methods don't have a prototype
property with a mostly-empty object assigned to it.)
Method syntax was introduced in ES2015. It's present in all modern browsers, and not in obsolete browsers like Internet Explorer (not even IE11).