473,714 Members | 2,464 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

JavaScript inheritance: How to call my parent method?

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.
Any idea?

Thanks.
Jun 27 '08 #1
6 14874
howa wrote:
[snip]
>

Any idea?

Try googling "javascript inheritance"
Jun 27 '08 #2
On Jun 11, 5:17 pm, howa wrote:
Consider example:

Animal = function(age) {
this.age = age;

};
Why no declaration for the - Animal - variable, and why assign a
function expression here when a function declaration would be the more
natural means of getting the constructor into existance?
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.

Any idea?
If you must then:-

Human.prototype .sleep = function() {
Animal.prototyp e.sleep.call(th is);
};

- will do what you ask, but you should be able to design that desire
out of system.

Richard.
Jun 27 '08 #3
Henry <rc*******@rain drop.co.ukwrite s:
If you must then:-

Human.prototype .sleep = function() {
Animal.prototyp e.sleep.call(th is);
};

- will do what you ask, but you should be able to design that desire
out of system.
Agreed, though there are some situations where this is more or less
the only sane solution and trying to design it away won't make things
better. Inheritance already couples the objects pretty rigidly, so one
more reference to the "super" object won't hurt much.

J.

--
Joost Diepenmaat | blog: http://joost.zeekat.nl/ | work: http://zeekat.nl/
Jun 27 '08 #4
howa <ho******@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();
Ok, considering this example, you say that all humans inherit
from the same animal. Not from the "class" of objects created
by the Animal constructor, but from a specific object.

That's just wrong.

The animal used as prototype for humans doesn't have an age,
like other animals (or rather, it does have an "age" property,
but with the "undefined" value). If it did have an age, a proper
animal, then all humans would inherit that same date.
Inheritance in Javascript is between objects, not between
constructors (and not between classes, since there are none).
You appear to be trying to do class based inheritance in
Javascript. While probably possible to emulate, it won't
be easy, nor natural.
Human.prototype .sleep = function() {
// How to call my parent sleep();
Others have given examples. Another extreme example would be:

Human.prototype .sleep = function() {
delete this.sleep;
this.sleep();
this.sleep = arguments.calle e;
}

Again, it's not something you want to do. Rather do something like:

Human.prototype .sleep = (function(){
var parentSleep = Human.prototype .sleep; // original value
return function() {
// something
parentSleep.cal l(this);
}
})();
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jun 27 '08 #5

Howa,

howa <ho******@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.

Using the YAHOO!'s YUI class-based-inheritance-emulating functions, you
could do (untested)

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);

... // do some more stuff
}
-----

HTH,
Arnaud


>

Any idea?

Thanks.
Jun 27 '08 #6
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

Jun 27 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
4799
by: RR | last post by:
I have two classes: class Base { function Insert() { // does stuff } }
2
3874
by: lkrubner | last post by:
My code was dying on the line below where I use method_exists: if (class_exists($nameOfClassToBeUsed)) { $object = new $nameOfClassToBeUsed(); $this->arrayOfAllTheObjectsSoFarLoaded = & $object; if (method_exists($object, "setCallingCode")) $object->setCallingCode($nameOfFunctionOrClassCalling); return $object; } else {
9
11573
by: keith | last post by:
I created a class libery which has name space Assembly and class Assembly and compiled it. Then created a C# project and called a method in the external class e.g. Assembly dll; dll=Assembly.LoadFrom(@"c:\app\Assembly.dll");
4
1679
by: Hadi | last post by:
Hello, Say I have three classes inheritance A <-- B <-- C And in A I have the Create method: class A { public override bool Create() {
33
1868
by: Partha Protim Roy | last post by:
Hello, I have a Customer form say A to enter/update customer details. In the Form A I have a button which opens another form say B. In the Form B, I am providing user with a option to search Customer from the database depending on various search criteria. On matching the criteria, list of Customer is displayed in the datagrid.
2
13462
by: engwar1 | last post by:
I have a page that my users will go to to upload files to my website. As I want to reuse the file upload code on multiple pages I put the file upload textbox/buttons on a user control which I plan to include in multiple aspx pages where they'll be able to upload images for other purposes. On the first page that I'm working on where users will be doing the upload (which I'll call the 'parent' page) I also have a DataGrid where I display...
9
5849
by: Steve Richter | last post by:
in a generic class, can I code the class so that I can call a static method of the generic class T? In the ConvertFrom method of the generic TypeConvert class I want to write, I have a call to the static Parse method of the conversion class. if (InValue is string) return T.Parse((string)InValue); else return base.ConvertFrom(context, culture, InValue);
4
5614
by: Steve Hershoff | last post by:
Hi everyone, We have a javascript function we'd like to call from within a C# method in our code-behind file. The way it has worked historically is we'd call the method from a hyperlink, like this: <a href='javascript:MyMethod(Param1, Param2)' runat="server" ID="MyLink">click here</a> ....what I'd like to do now is somehow call "MyMethod" from the code-behind
7
3826
gskoli
by: gskoli | last post by:
Dear all, Let me tell you the scenario , i have called javascript function on radio button selection , Ex. Suppose There are 3 Radio Button . Let us consider i have clicked on one radio button then javascript is called on that and it get 'checked' But again if if i clicked on that radio , Then again it will call the javascript . So i dont want to let it happen , If radio button value got changed then only javascript should...
0
8707
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9174
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9074
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9015
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6634
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5947
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4725
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3158
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2110
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.