Object.create, chaining and 'this'

Given the following program, console logs are correct - pay attention to the chain initand 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();
Run codeHide result

My question is: how and why return thisis it required for its work? See the error below:

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

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

MDN claims that Object.create returns a new object, so the init () chain should work ... Thinking about it ... is it because the new object that was chained remains "anonymous"?

Note that if it init()gets its own string, everything works as I would expect, without the need return this:

const fluffy = Object.create(cat);
fluffy.init('meeeaaaahuuu');
fluffy.makeSound();
+6
source share
2 answers

, :

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

, fluffy Object.create. const fluffy = Object.create(cat).init('meeeaaaahuuu');, init Object.create init to fluffy, undefined .

+14

@zerkms, init return, undefined.

fluffy , init

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

init return, fluffy undefined

console.log(fluffy); // undefined

init , cat, fluffy .

, const fluffy = Object.create(cat).init('meow');

let fluffy = Object.create(cat);
fluffy = init('meow');
+4

All Articles