Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

javascript - Prototypal inheritance and new keyword

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Remember that a prototype is an instance of the parent type. Using child.prototype = parent.prototype would 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.

Child.prototype.childOnlyValue = 5;
// WARNING: Parent.prototype.childOnlyValue is now also 5,
//             because Parent.prototype === Child.prototype

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...