开发者

Inherit all methods of object (including "constructor"), but modify some of them

开发者 https://www.devze.com 2022-12-30 12:05 出处:网络
Let\'s imagine that we have object Animal $.Animal = function(options) { this.defaults= { name : null }

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!");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号