Method Syntax in Object Literal notation?

21 views Asked by At

I'm new to JavaScript and I'm having a little trouble with execution context; the value of this.

Consider the following:

const name = "Mary";

const proto = { 
  hello: () => `Hello, my name is ${ this.name }.`
};

const greeter = name => Object.assign(Object.create(proto), { name }); 

const joe = greeter("Joe");

console.log(joe.hello());

I expected the log would be: Hello, my name is Joe. But this was instead the global object. It returned Hello, my name is Mary.

On the other hand:

const name = "Mary";
const proto = { 
  hello() { return `Hello, my name is ${ this.name }.` }
};

const greeter = name => Object.assign(Object.create(proto), { name }); 

const joe = greeter("Joe");

console.log(joe.hello());

This time the expected string was returned; the only difference is the "method definition" inside the proto object.

So my question is what is the second syntax even called? It is not a function declaration nor a function expression, so what is it? Either way I expected the property accessor invocation from the 'greeter' object, 'joe' to associate this to the object itself.

And when should I use a function expression and when should I use this alternative form of declaring an object's method?

I hope this makes sense and thank you in advance for you attention.

0

There are 0 answers