views:

37

answers:

1

Hello,

Let's imagine that we have object Animal

$.Animal = function(options) {
  this.defaults  = { name : null }
  this.options   = $.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.

A: 

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!");
}
mck89
Where can I read more about this method? I can't understand why you're doing this way.
Kirzilla
If i remember well it was written in the YUI library anyway the concept is that you get the constructor of the first object and assign it to the second one, then you copy the prototype object of the first object and assign it to the second one. I don't think that this is different from the classic for(c in obj.prototype) loop to copy the prototype object but it is certain faster.
mck89
And remember that the prototype object must be copied you cannot assign the prototype like $.Dog.prototype=$.Cat.prototype because that is not a copy but a reference to the $.Dog.prototype and if you modifiy the prototype on the Cat it changes also on the Dog
mck89