gpt4 book ai didi

javascript - JS 原型(prototype)继承 : childs use the same parent properties?

转载 作者:数据小太阳 更新时间:2023-10-29 06:12:20 27 4
gpt4 key购买 nike

假设我有 Player 对象:

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

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

效果很好,我可以创建播放器,每个播放器都有自己的一组处理程序。现在假设我需要从 player 继承:

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

testPlayer.prototype = new player();

现在,当我创建 testPlayer 时,它们中的每一个都共享相同的 handlers 属性:

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

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

我在这里错过了什么?我知道每个 testPlayer 的原型(prototype)都是我在描述子类时创建的同一个 new player 对象。但是有没有办法让所有的 testPlayer 都有自己的一组处理程序?

最佳答案

对于那些习惯于经典继承的人来说,这肯定看起来很奇怪,但这就是原型(prototype)继承的工作原理。要让每个实例都有一个单独的处理程序对象,您需要在子构造函数中指定一个。这将隐藏原型(prototype)的同名属性:

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

testPlayer.prototype = new player();

另一种解决方案是根据您的 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);
}

有趣的事实

只有在修改原型(prototype)上的对象(或数组)的属性时才会出现这个问题。如果您尝试分配给原型(prototype)上的属性,将自动创建一个本地阴影属性(您不能从实例分配给原型(prototype)属性)。

关于javascript - JS 原型(prototype)继承 : childs use the same parent properties?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15793985/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com