Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is function keyword optional while creating an object? [duplicate]

Tags:

javascript

       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?

like image 871
prettyversatile Avatar asked Jan 31 '26 03:01

prettyversatile


1 Answers

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).

like image 76
T.J. Crowder Avatar answered Feb 02 '26 18:02

T.J. Crowder