3

function foo(name) {
    this.name = name;
}

foo.prototype.getName = function() {
    return `Hello ${this.name}!`;
}

function bar(name) {
    foo.call(this, name);
    this.name = name;
}

bar.prototype = Object.create(foo.prototype);
// bar.prototype = new foo();
// bar.prototype = Object.create(new foo());

bar.prototype.constructor = bar;

var b = new bar('John Doe');
console.log(b.getName());

What is the difference between these three ways?

bar.prototype = Object.create(foo.prototype);

bar.prototype = new foo();

bar.prototype = Object.create(new foo());
nircraft
  • 8,242
  • 5
  • 30
  • 46
  • 2
    Have you used a debugger to inspect the layout of the three different values? It's pretty easy to verify for yourself what the differences are in that regard. – Patrick Roberts Sep 20 '19 at 19:12
  • The difference between the first two is covered in [Understanding the difference between Object.create() and new SomeFunction()](https://stackoverflow.com/q/4166616/215552) – Heretic Monkey Sep 20 '19 at 19:16
  • 1
    Related: https://stackoverflow.com/q/4166616/1541563, https://stackoverflow.com/q/2709612/1541563, https://stackoverflow.com/q/50074294/1541563 – Patrick Roberts Sep 20 '19 at 19:18
  • The third is useless, the second calls the constructor, and the first is the way to go:) – Jonas Wilms Sep 20 '19 at 19:32

0 Answers0