Inherit all methods of object (including "constructor"), but modify some of them
Let's imagine that we have object Animal
$.Animal = function(options) {
this.defaults = { name : null }
this.opti开发者_JS百科ons = $.extend(this.defaults, options);
}
$.Animal.prototype.saySomething = function() {
alert("I'm animal!");
}
Now I'd like to create Cat object. It is absolutely similar to $.Annimal, but method saySomething() will look like this one...
$.Cat.prototype.saySomething = function() {
alert("I'm cat!");
}
How can I inherit from Animal to create new object Cat and redefine saySomething() method?
Thank you.
Try this one:
$.Cat=$.Dog.constructor; //Set the constructor
$.Cat.constructor=$.Dog.constructor;
var Native=function(){}; //Copy the prototype object
Native.prototype=$.Dog.prototype;
$.Cat.prototype=new Native();
//Assign new method
$.Cat.prototype.saySomething = function() {
alert("I'm cat!");
}
精彩评论