2012-05-08 8 views
0

我想将方法​​添加到克隆的原型类属性。我已经粘贴下面的代码。我想克隆一个JavaScript类。将方法添加到克隆的属性而不实际覆盖现有方法?

当我向这段代码中添加方法时,它会写入超类中定义的内容。

<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> 

回答

2

您需要延长movement对象,而不是将其覆盖:

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

谢谢,我在找什么! – richwestcoast

1

由于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"); 
访问它也扩展它