First appearing in ECMAScript 2015 (also known as ES2015 or ES6), method definitions are a shorthand for defining a function property in an object initializer (also known as an object literal). Although they are most often used for their brevity, they have some important semantic differences from function properties. This is to make them more consistent with methods in classes.
What is a method definition?
Consider the following object that is referenced by the person
constant. Its greet
property is assigned to a function. Before ES6, this was the only way to define a “method” on an object. It is known as a function property.
const person = {
name: "Kieran",
greet: function () {
return "Hi, my name is " + this.name + ".";
},
};
In ES6 and beyond, you can remove the colon (:
) and the function
keyword to create a method definition:
const person = {
name: "Kieran",
greet() {
return "Hi, my name is " + this.name + ".";
},
};
The super
keyword
Let’s start with something methods can do that function properties can’t. Methods can use the super
keyword to access properties on the prototype of the object that they are initialized on. In this example, the object referenced by the jacuzzi
constant shadows (overrides) the name
property of its prototype. However, the getInfo()
method can still access the name
property of the prototype using the super
keyword.
const jacuzzi = {
name: "Jacuzzi",
getInfo() {
return `A ${this.name} is a type of ${super.name}.`;
},
__proto__: {
name: "hot tub",
},
};
jacuzzi.getInfo(); // "A Jacuzzi is a type of hot tub."
Learn more:
If you try to use the super
keyword in the body of a function property, you’ll get a SyntaxError
:
const jacuzzi = {
name: "Jacuzzi",
getInfo: function () {
return `A ${this.name} is a type of ${super.name}.`; // SyntaxError
},
__proto__: {
name: "hot tub",
},
};
Methods cannot be used as contructors
Now for something function properties can do that methods can’t. Function properties can be used as constructors.
const obj = {
Person: function (name) {
this.name = name;
},
};
new obj.Person("Kieran"); // Person { name: "Kieran" }
If you try to use a method as a constructor, you’ll get a TypeError
:
const obj = {
Person(name) {
this.name = name;
},
};
new obj.Person("Kieran"); // TypeError
Summary
First introduced in ES6, method definitions are a shorthand for properties assigned to functions. They have two semantic differences from function properties:
- Methods have access to the
super
keyword. - Methods cannot be used as constructors.