On Jun 13, 8:41 am,
a...@remove.thi s.and.keep.what .follows.ionics oft.com (Arnaud Diederen
(aundro)) wrote:
Howa,
howa <howac...@gmail .comwrites:
Consider example:
Animal = function(age) {
this.age = age;
};
Animal.prototyp e.sleep = function() {
alert("Animal Sleeping...");
};
Human = function(name, age) {
this.name = name;
this.age = age;
};
Human.prototype = new Animal();
Human.prototype .sleep = function() {
// How to call my parent sleep();
};
var h = new Human("Peter", 15);
h.sleep();
I want inside the sleep() method of Human class, call to its parent
sleep() method.
I would do just exactly that - explicitly:-
sleep : function(t) {
Animal.prototoy pe.sleep.call(t his, t);
}
>
Using the YAHOO!'s YUI class-based-inheritance-emulating functions, you
could do (untested)
The OP is interested in understanding how to solve the problem.
The function itself, with my comments interspersed:-
/**
* Utility to set up the prototype, constructor and superclass
properties to
* support an inheritance strategy that can chain constructors and
methods.
* Static members will not be inherited.
*
* @method extend
* @static
* @param {Function} subc the object to modify
* @param {Function} superc the object to inherit
* @param {Object} overrides additional properties/methods to add
to the
* subclass prototype. These will
override the
* matching items obtained from the
superclass
* if present.
*/
extend: function(subc, superc, overrides) {
if (!superc||!subc ) {
// GS: Safe to omit - new - keyword.
throw new Error("extend failed, please check that " +
"all dependencies are included.");
}
var F = function() {};
F.prototype=sup erc.prototype;
subc.prototype= new F();
subc.prototype. constructor=sub c;
subc.superclass =superc.prototy pe;
// GS: Consider using === (may result in increased performance in
JScript).
if (superc.prototy pe.constructor ==
Object.prototyp e.constructor) {
superc.prototyp e.constructor=s uperc;
}
if (overrides) {
for (var i in overrides) {
// GS: Important call to hasOwnProperty.
if (L.hasOwnProper ty(overrides, i)) {
subc.prototype[i]=overrides[i];
}
}
L._IEEnumFix(su bc.prototype, overrides);
}
},
Another possibility is to cache the function being new'd. One possible
way to accomplish this is to use the one the Activation object is in -
arguments.calle e:-
var f = arguments.calle e;
But this requires a check in the - extend - function, which gets
recursed.
if(arguments.le ngth === 0) return;
It's good to see that YAHOO has finally fixed some of the significant
bugs in this code.
Animal = function (a) {
...
}
Animal.prototyp e.sleep = function (t) {
...
}
Human = function (a) {
Animal.apply (this, arguments);
}
YAHOO.extend (Human, Animal);
Human.prototype .sleep = function (t) {
... // do some stuff
Human.superclas s.sleep.call (this, t);
Did you mean:
Human.superclas s.prototype.sle ep.call(this, t)
- ?
Or more explicit:-
Animal.prototyp e.sleep.call(th is, t);
Garrett
>
HTH,
Arnaud