我想克隆一个 javascript 类. 将方法添加到克隆的属性中,而不实际覆盖现有方法
I want to clone a javascript class. add methods to the cloned property without actually overwriting the exisiting methods?
我正在尝试将方法添加到克隆的原型类属性中。我已经粘贴了下面的代码。
在我向这段代码添加方法的那一刻,它会过度写入超类中定义的内容。
<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)
}
});
由于movement
是一个对象,因此您还必须通过使用原型访问它来扩展它
var Animal = Class.create({
initialize: function(name, sound) {
this.name = name;
this.sound = sound;
},
movement: {
move: function(direction) {
alert('moving: ' + direction);
}
}
});
var AnimalClone = Class.create({});
AnimalClone.prototype = Object.extend(new Animal(),{});
AnimalClone.prototype.movement = Object.extend(AnimalClone.prototype.movement, {
jump: function(height) {
alert('jumped:' + height);
}
});
var animalClone = new AnimalClone;
animalClone.movement.move("up");
animalClone.movement.jump("10mts");
相关文章:
- 当属性不一致时,如何根据属性对JS对象列表进行排序
- Css order属性不't在Jquery设置时更新
- Bookshelf.js设置的属性不在数据库中
- 查找数组's按属性不存在于另一个数组中的对象
- 在javascript函数调用中传递的HTML属性不完整
- 在jQuery中链接时CSS属性不起作用
- 设置AngularJS控制器属性不能是使用Coffeescript的最后一行
- 向插件添加属性(不是默认方式)
- Css 属性不会更改(javascript)
- 函数中的 angularJS 访问对象属性不起作用
- JavaScript - 对象属性不一致
- 调用按键事件而不实际按下 JavaScript 中的键
- 获取脚本中CSS颜色属性的实际值
- 如何在不实际使用<表单>
- 控制器的属性不会动态更改
- Express和Typescript-Error.stack和Error.status属性不存在
- 使用 css() 更改自定义属性不起作用
- 自定义CSS复选框jQuery诱导的“;“已检查”;属性不't在视觉上”;“检查”;复选框
- 具有多个依赖项的Ember属性不会按预期更新
- 我想克隆一个 javascript 类. 将方法添加到克隆的属性中,而不实际覆盖现有方法