In backbone.js under the inherits method, the authors does this:
var ctor = function() {};
// some other code ...
var child;
// some other code ...
ctor.prototype = parent.prototype;
child.prototype = new ctor();
The above as I understand it is to allow the new object to inherit the prototypical chain of the parent. I’m trying to wrap my head around this, but in practice, is there a difference between the above and assigning the prototype directly?
child.prototype = parent.prototype
I understand that there exists this [[prototype]] object that cannot be accessed directly unless through the new keyword. However, given that most object declarations are of the form
var SomeObj = function() {};
SomeObj.prototype.test = function() { return "Hello World"; }
What would be the practical differences in the above prototype assignments?
Remember that a prototype is an instance of the parent type. Using
child.prototype = parent.prototypewould set the child’s prototype equal to the parent’s prototype, rather than an prototypical instance of the parent.Here’s a huge problem that arises if you use
child.prototype = parent.prototype: if you try to alter the child’s prototype, you’re also altering the parent’s prototype, because they are the same object.Creating the new instance of the parent is absolutely necessary. Otherwise, you’ll have a flat prototype chain with a single shared prototype, so you’ll have problems like the one I’ve outlined above.