calipoop calipoop -4 years ago 34
Javascript Question

Object.create, chaining and 'this'

Given the following program, console logs correctly - note the chained 'init' function and 'return this':



const cat = {
init(sound) {
this.sound = sound;
return this;
},
makeSound() {
console.log(this.sound);
}
};

const fluffy = Object.create(cat).init('meeeaaaauuu');
fluffy.makeSound();





My question: how and why is 'return this' required for it to work? See error below with it removed:



const cat = {
init(sound) {
this.sound = sound;
// return this
},
makeSound() {
console.log(this.sound);
}
};

const fluffy = Object.create(cat).init('meeeaaaahuuu');
fluffy.makeSound();





MDN states Object.create returns the new object, so chaining init() should work... Thinking it through... is it because the new object that's chained is still 'anonymous'?

Note that if init() gets its own line, all works as I would expect, without needing 'return this':

const fluffy = Object.create(cat);
fluffy.init('meeeaaaahuuu');
fluffy.makeSound();

Answer Source

The reason this works:

const fluffy = Object.create(cat);
fluffy.init('meeeaaaahuuu');
fluffy.makeSound();

is because you're assigning fluffy the return value of Object.create. When you do const fluffy = Object.create(cat).init('meeeaaaahuuu');, you're calling init on the return value of Object.create, and assigning the return value of init to fluffy, which is undefined without a return statement.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download