3 ms·
> Spy.prototype = new Person(); Don't do it that way. If the Person constructor assigns any data, for example an array, that data will be shared with all insta
by MatthewPhillips 14y ago
> Spy.prototype = new Person();
Don't do it that way. If the Person constructor assigns any data, for example an array, that data will be shared with all instances of Spy. Most likely you don't want that. Instead call the Person constructor within the Spy constructor:
function Spy() {
Person.apply(this, arguments);
}
Spy.prototype = Person.prototype;
Spy.prototype.constructor = Spy;
- jashkenas 14y agoDude, that's a pretty awful way to do it. After running your example code: (new Person).constructor === Spy
- insin 14y agoPerson will also have anything you add to Spy's prototype if you do that. Attaching the "parent" prototype you want to have in the "child" prototype chain to a dummy constructor and new-ing that will do the trick for widest compatibility, although Object.create in ES5 and __proto__ (standardised) in ES6 both give you more direct access to the prototype chain: function inherits(child, parent) { var dummy = function() {} dummy.prototype = parent.prototype child.prototype = new dummy() child.prototype.constructor = child } function Spy() { Person.apply(this, arguments) } inherits(Spy, Person)