let username = {
name: 'John Smith',
yearBorn: 2001,
age (){
return 2020 - this.yearBorn;
}
}
console.log(username.age());
As you can see, I'm not using function expression here nor I'm doing standard function by using the function keyword yet its working perfectly fine!
Is it safe to assume that function keyword is optional when you're creating a JS object?
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:
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.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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With