gpt4 book ai didi

javascript - 我想克隆一个 javascript 类。向克隆属性添加方法而不实际覆盖现有方法?

转载 作者:行者123 更新时间:2023-11-28 21:03:14 24 4
gpt4 key购买 nike

我正在尝试向克隆的原型(prototype)类属性添加方法。我已粘贴下面的代码。

当我向这段代码添加方法时,它会覆盖父类(super class)中定义的内容。

<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js" type="text/javascript"></script>
<script type="text/javascript">
var Animal = Class.create({
initialize: function(name, sound) {
this.name = name;
this.sound = sound;
},

speak: function() {
alert(this.name + " says: " + this.sound + "!");
}
});

Animal.movement = {
move: function(direction){
alert('moving: ' + direction)
}
}

var AnimalClone = { }
Object.extend(AnimalClone, Animal);

//Now i want to add 'jump' to this list of methods
//without over writing the inherited 'move' method
AnimalClone.movement = {
jump: function(height){
alert('jumped:' + height)
}
}
</script>

最佳答案

您需要扩展movement对象,而不是覆盖它:

Object.extend(AnimalClone.movement, {
jump: function(height){
alert('jumped:' + height)
}
});

关于javascript - 我想克隆一个 javascript 类。向克隆属性添加方法而不实际覆盖现有方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10497906/

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