JS Prototypal Inheritance: Do children use the same parental properties?

Let's say I have a Player object:

var player = function(name) {
    this.handlers = {};
}

player.prototype.on = function(event, callback) {
    if (!this.handlers[event]) {
        this.handlers[event] = [];
    }
    this.handlers[event].push(callback);
}

It works great, I can create players, and each of them will have its own set of handlers. Now suppose I need to inherit from player:

var testPlayer = function(name) {
    this.name = name;
};

testPlayer.prototype = new player();

Now, when I create testPlayer, each of them has the same property handlers:

var adam = new testPlayer('Adam');
adam.on('test', function(){});

var eve = new testPlayer('Eve');
// eve.handlers == {'test':<function>}

What am I missing here? I understand that every prototype testPlayeris the same object new playerthat I create when describing a child class. But is there some way for all testPlayers to have their own set of handlers?

+5
source share
2 answers

, , . - , . :

var testPlayer = function(name) {
    this.name = name;
    this.handlers = {};
};

testPlayer.prototype = new player();

shadowing , on:

player.prototype.on = function(event, callback) {
    // Check for a handlers property on the instance
    if(!this.hasOwnProperty('handlers') {
        this.handlers = {};
    }
    if (!this.handlers[event]) {
        this.handlers[event] = [];
    }
    this.handlers[event].push(callback);
}

, ( ) . , , ( ).

+5

, handlers - , , ,

testPlayer.prototype = new player();

player testPlayer.prototype handlers.

, handlers testPlayer, handlers, , testPlayer.

, on testPlayer.prototype.handlers, adam.handlers eve.handlers.

, :

var testPlayer = function(name) {
    this.name = name;
    this.handlers = {};
};
+1

All Articles