How JS evaluates the expression ({...}).objMethod()?

47 Views Asked by At

From my limited knowledge of how expression are evaluated in JS, in the code below, I know that parenthesis makes JS engine evaluates whatever is inside the parenthesis, as an expression ({..}) so ({..}) this will evaluate to the object {...} being returned to the global scope (in this case, << Am I right? pls correct me if not) or whatever the scope the expression is in.

But what I don't understand is how the greet function ({...}).greet() gets evaluated in the scope/context of the returned object from the expression ({..}). Generally at-least I would assign the returned value of the expression to a variable/reference to the returned obj and then call the greet() method of that obj, as in

var x = ({...})
x.greet()

then, how the following code is evaluated.

({
  name: "John Doe",
  data: {
    message: "Hello World"
  },
  greet: function(){
    console.log("I am " + this.name);
    console.log("I have a message for you: " + this.data.message);
  }
}).greet();

Thanks

1

There are 1 best solutions below

2
Jack Bashford On

Just how you'd expect, it's just evaluating the object, then calling the greet method on it. It's like this:

console.log({ foo: 1 }.foo);

Except with a method. Also note that the parentheses are optional in the statement above, but are required in your question.