Reputation: 107
I am trying to add methods to a cloned a prototype class property. I have pasted the code below.
At the moment when i add methods to this snippet of code it over writes whats been defined in the 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>
Upvotes: 0
Views: 91
Reputation: 25145
As movement
is an object, you have to extend it also by accessing it using the prototype
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");
Upvotes: 1
Reputation: 339856
You need to extend the movement
object, not overwrite it:
Object.extend(AnimalClone.movement, {
jump: function(height){
alert('jumped:' + height)
}
});
Upvotes: 2