ES6:19 Write Concise Declarative Functions with ES6
When defining functions within objects in ES5, we have to use the keyword function as follows:
Refactor the function setGear inside the object bicycle to use the shorthand syntax described above.
const person = {
name: "Taylor",
sayHello: function() {
return `Hello! My name is ${this.name}.`;
}
};
With ES6, You can remove the function keyword and colon altogether when defining functions in objects. Here's an example of this syntax:
name: "Taylor",
sayHello: function() {
return `Hello! My name is ${this.name}.`;
}
};
const person = {
name: "Taylor",
sayHello() {
return `Hello! My name is ${this.name}.`;
}
};
name: "Taylor",
sayHello() {
return `Hello! My name is ${this.name}.`;
}
};
const bicycle = {
gear: 2,
setGear: function(newGear) {
"use strict";
this.gear = newGear;
}
};
bicycle.setGear(3);
console.log(bicycle.gear);
the shorthand syntax described
gear: 2,
setGear: function(newGear) {
"use strict";
this.gear = newGear;
}
};
bicycle.setGear(3);
console.log(bicycle.gear);
const bicycle = {
gear: 2,
setGear(newGear) {//instead of : function(newGear)
"use strict";
this.gear = newGear;
}
};
bicycle.setGear(3);
console.log(bicycle.gear);
gear: 2,
setGear(newGear) {//instead of : function(newGear)
"use strict";
this.gear = newGear;
}
};
bicycle.setGear(3);
console.log(bicycle.gear);
Comments
Post a Comment