0

Usual way to implement inheritance in javascript is something like:

function Person(name, surname) {
  this.name = name;
  this.surname = surname;
}

Person.prototype.whoAmI = function() {
  console.log("I'am " + this.name + " " + this.surname);
}

function Ninja() {
  Person.apply(this, arguments); // call to parent constructor
}

Ninja.prototype = new Person();
Ninja.prototype.constructor = Ninja;

var ninja = new Ninja("John", "Doe");
ninja.whoAmI();

From backbone what i can see is use of "Surrogate" function like: (very simplified example of what i can extract like example from Backbone source code)

function Person(name, surname) {
  this.name = name;
  this.surname = surname;
}

Person.prototype.whoAmI = function() {
  console.log("I'am " + this.name + " " + this.surname);
}

function Ninja() {
  Person.apply(this, arguments);
}

var Surrogate = function() { this.constructor = Ninja; }
Surrogate.prototype = Person.prototype;
Ninja.prototype = new Surrogate();

var ninja = new Ninja("John", "Doe");
ninja.whoAmI();

From what i can understand, these examples work exactly same so why need for Surrogate function. I find one comment in the source about this:

Set the prototype chain to inherit from parent, without calling parent's constructor function.

Why not calling parent constructor function?

Srle
  • 10,366
  • 8
  • 34
  • 63

1 Answers1

3

Why not calling parent constructor function?

Because we want to constructor function to be only called when an instance is created. The Ninja.prototype however is not an instance of Person, it should not have name or surname properties - it should only inherit the whoAmI method. See also What is the reason to use the 'new' keyword at Derived.prototype = new Base for details.

Usual way to implement inheritance in javascript is something like

Only "something like". The correct way is not to call the parent constructor, but we don't need that Surrogate thingy for that. The standard is just to use Object.create:

Ninja.prototype = Object.create(Person.prototype);
Ninja.prototype.constructor = Ninja;

(for compatibility with ES3 environments just shim Object.create instead of littering your source code with Surrogate functions)

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375