1

Lately, I was going through some Javascript code. I was confused to see something like this in the code. A method declared and defined inside an object literal. Even though this is common in Javascript, there was no property name assigned to that function. Just plain function along with the other properties of the object. I saw something like this.

    let myObject = {
    name: 'my name',
    sayHello(){
    console.log('This is ' + this.name);
    }
    }

    myObject.sayHello();

Curious, I copied the code into the console and found it to work. Can someone explain the mystery behind it? Doesn't it break the default convention that all properties must have a name within an object literal?

Shouldn't this be like this?

        let myObject = {
        name: 'my name',
        sayHello: function(){
        console.log('This is ' + this.name);
        }
        }

        myObject.sayHello();
samuellawrentz
  • 1,662
  • 11
  • 23

0 Answers0