473,749 Members | 2,463 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Constructor is never called

Jun
I have following script

<script>
var Animal = function(name){
this.name = name;
}
Animal.prototyp e.eat = function (food)
{
alert(this.name + " eat " + food);
}

//constructor for Dog
var Dog = function(){
}

//"inheriting " from Animal
Dog.prototype = new Animal();
Dog.prototype.c onstructor = Animal;

var myDog = new Dog("ddd");

myDog.eat("bone ");

</script>

The result was that Dog's constructor was called but Animal's constructor
was never called so I got "undefined eat bone".

Is the javascript inheritant doesn't support calling super constructor or
I didn't use "Dog.prototype. constructor" correctly?

thanks
Jul 20 '05 #1
3 4569

"Jun" <ju*********@ho tmail.com> schreef in bericht
news:de******** *************** ***@posting.goo gle.com...

The result was that Dog's constructor was called but Animal's constructor
was never called so I got "undefined eat bone".

Is the javascript inheritant doesn't support calling super constructor or
I didn't use "Dog.prototype. constructor" correctly?


Actually, it is called. But since you are not passing it an argument and the
Dog constructor doesn't set the name property, it remains undefined.

To fix this, you could either pass the argument to the Dog constructor:

//constructor for Dog
var Dog = function(name) {
this.name = name;
}

or pass it when initiating the prototype property:
Dog.prototype = new Animal("ddd");

Anither option is to define a setter method in the Animal constructor
function:

var Animal = function() {
this.setName = function (name) {
this.name = name;
};
}

This can then be called seperatly to set the dog's name:
.....
var myDog = new Dog();
myDog.setName(" goofy");

myDog.eat("bone ");
.....

JW

Jul 20 '05 #2
ju*********@hot mail.com (Jun) writes:
<script>
For pedantic reasons, I'll remind you (and everybody else :) that the
type attribute is required in HTML 4 and later.

<script type="text/javascript">
var Animal = function(name){
this.name = name;
} Animal.prototyp e.eat = function (food)
{
alert(this.name + " eat " + food);
}

//constructor for Dog
var Dog = function(){
As Janwillem Borleffs said, you don't set the name.
Javascript doesn't call the superclass' constructor, mostly because
there are no classes in Javascript at all, so no superclasses either.
If you want to call the superclass' constructor, you have to do
it manually:
Animal.call(thi s,arguments[0]);
or just (since you set it up with "Dog.prototype. constructor = Animal;")
this.constructo r(arguments[0]);
(you might want to make Dog take an argument :)
}

//"inheriting " from Animal
Don't say "inheriting ". It isn't. Javascript is prototype based, not
class based, so there is no real inheriting.
Dog.prototype = new Animal();
This means that a new Dog object will have a [[prototype]] reference
to an Animal object with an undefined name (you call Animal with
no argument, so the name gets set to undefined)>
Dog.prototype.c onstructor = Animal;
The prototype's constructor is never called automatically. If you
want to call it, you must do it yourself.
The result was that Dog's constructor was called but Animal's constructor
was never called so I got "undefined eat bone".
You called it yourself in
"dog.protot ype = new Animal();"
It is never called automatically.
Is the javascript inheritant doesn't support calling super constructor or
I didn't use "Dog.prototype. constructor" correctly?


There is no inheritance. You didn't say what you expected
Dog.prototype.c onstructor to do, but it probably doesn't do what you
expect. (When asking for help, always say both what actually happenes
and what you expected to happen).

/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.'
Jul 20 '05 #3
Fox


Jun wrote:

I have following script

<script>
var Animal = function(name){
this.name = name;
}

Animal.prototyp e.eat = function (food)
{
alert(this.name + " eat " + food);
}
If you *know* you're going to include this method -- just declare it
within the object definition:

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

this.eat = function(food)
{
alert(this.name + " eats " + food);
}
}
Use prototype for predefined objects like Array, Number, String, etc...
or declaring superclasses...

//constructor for Dog
var Dog = function(){
}
This is not an object (much less a constructor) -- it's an empty
function... in order to be considered an object, it *requires* at least
one property or method utilizing the keyword "this".
//"inheriting " from Animal
Dog.prototype = new Animal();
Dog.prototype.c onstructor = Animal;
Not required and not recommended -- the constructor is automatically
Animal (or whatever topmost level object is utilized).

var myDog = new Dog("ddd");

myDog.eat("bone ");

</script>

The result was that Dog's constructor was called but Animal's constructor
was never called so I got "undefined eat bone".

Is the javascript inheritant doesn't support calling super constructor or
I didn't use "Dog.prototype. constructor" correctly?
answered...

thanks


The "super" constructor IS automatically called as soon as it is
prototyped from the "subclass" [or, probably, more technically, as soon
as the object prototyped is parsed since you can prototype the
superclass prior to defining it] -- it becomes, essentially, the *only*
constructor used for the object.

Dog's constructor (if Dog is actually an Object) is not Dog, it's
Animal, as you will see from the alerts:
function
Animal(args)
{
this.genus = args;

alert("construc tor called -- animal genus = " + this.genus);
// fires when called...

// use a JS superclass as repository
// for common properties or methods

this.getType = function()
{
alert (this.type); // declared in Dog
}
this.getBreed = function()
{
alert (this.breed); // declared in Cat
}

}

function
Dog(arg)
{
alert(this.cons tructor); // shows function Animal
this.type = arg;

}

function
Cat(arg)
{
alert(this.cons tructor); // shows function Animal
this.breed = arg; // different than Dog...
}

// the point of subclassing is to have different sets of properties and methods
// particular to that class -- the super providing all of the common properties
// and methods...

Dog.prototype = new Animal("canis") ; // args common to ALL Dog objects
Cat.prototype = new Animal("felis") ; // args common to ALL Cat objects

// note -- do not use Cat/Dog.prototype.c onstructor
// the constructor is automatically set by JS and
// in this case, the constructor => "Animal" [the entire function
declaration]
// It is at this point that the "superclass " constructor is "fired"
// you get the "constructo r called..." alert -- 2 in a row
var d = new Dog("doberman") ;
var c = new Cat("siamese");

// these fire the constructor Animal alerts and set their respective
"local" properties
// as per the instructions within these object declarations
// use subclass reference to access superclass/inherited methods/properties:
d.getType();
d.getBreed(); // shows "undefined"
c.getType(); // shows undefined
c.getBreed();

alert(d.genus + "\n" + c.genus); // shows "superclass " property of instance

Taking this even further, you have the case of extending the subclass
with yet another subclass:

function
dogFood(brand)
{
alert(this.cons tructor); // again -- will show Animal!
this.brand = brand;
}

dogFood.prototy pe = new Dog("all breeds"); // notice -- NOT Animal here
Even though Dog is used as the prototype declaration, you will see that
Animal is actually the constructor called [since it is the constructor
for Dog and Cat] -- "all breeds" is loaded into the Dog instance's type
property as default and:

var df = new dogFood("purina ");

will load "purina" into the brand property.

df.genus will show "canis" and calling df.getType() will fire the alert
showing "all breeds" as the type.
Now, for fun, put:

function
Lifeform(kind)
{

this.lifeform = kind;

this.showAll = function()
{
var s = "";
for(var i in this)
{
s += i + ": " + this[i] + "\n";
}

alert(s);
}
}

Animal.prototyp e = Lifeform("fur-bearin' critter");
// can be declared BEFORE Animal is actually declared

at the head of everything above...

and

d.showAll(); // called from Dog instance
and
df.showAll(); // called from dogFood instance

to observe the differences between object instances... what you end up
with is a large object with everything included -- essentially something like:

var dog = new (Dog + Animal + Lifeform); // very pseudocode...
// no such thing in JS
var cat = new (Cat + Animal + Lifeform);

var dogfood = new (dogFood + Dog + Animal + Lifeform);
You can change the "default" values passed to "superclass es" anytime you
wish by redeclaring the prototype:

dogFood.prototy pe = new Dog("my pet"); // changed from "all breeds"
var dogfood2 = new dogFood("iams") ;

Now compare df.showAll() and dogfood2.showAl l() -- you'll see that
df.type still shows "all breeds" and "purina" while dogfood2.type
(default) has changed to "my pet" and brand to "iams". The new
prototype takes effect for all subsequent instantiations of class
dogFood (until explicitly changed). In other words, changing the
prototype does not change already existant instances of the object...
[you are not limited to redeclaring the prototype of the extended class
-- you could as easily redefine prototype new Animal("new default") or
Lifeform (etc) from any point in the "chain" of inheriting objects. This
gives JS a level of flexibility beyond that available from more
conventional class oriented objects where these kinds of "on-the-fly"
changes are not available.

Nowhere did I use .call() -- nowhere did I use .constructor... Objects
in JS are not that complicated. Logic dictates that there is inheritance
since methods and/or properties do not need to be redeclared in each
"class" declaration or overridden (although that is your option if you
so choose.) Although JS has a different object model than other
programming languages like Java, the *language* that we have to describe
object models in general is limited to a similar set of terms that are
used to describe both prototype based objects as well as class based
objects...so, superclass/subclass and inheritance are used to describe
similar *functionalitie s* in both even though there are syntactical
differences [there is, technically, no class declarator in JS; however,
there is likewise no terminology for superobject/subobject, super/sub
prototype, or super/sub function either]. Check out Netscape's
JavaScript User's Guide for an excellent description (and examples) of
the differences between prototype-based and class-based object oriented languages.
Hope this helps...
Jul 20 '05 #4

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

Similar topics

6
3470
by: Maria Gaitani | last post by:
Hi! I am trying to programme some java native interface but I'm still in the process of research. I've seen examples such as this one http://java.sun.com/docs/books/tutorial/native1.1/stepbystep/step1.html but I don't understand the third and fourth line of the code of the above example:
23
5180
by: Fabian Müller | last post by:
Hi all, my question is as follows: If have a class X and a class Y derived from X. Constructor of X is X(param1, param2) . Constructor of Y is Y(param1, ..., param4) .
24
3772
by: slurper | last post by:
i have the following class sequence { public: sequence (const sequence& mysequence, const int newjob) { job_sequence(mysequence.job_sequence) job_sequence.push_back(newjob); ... }
10
3565
by: John Brock | last post by:
I have a base class with several derived classes (I'm writing in VB.NET). I want each derived class to have a unique class ID (a String), and I want the derived classes to inherit from the base class *Shared* methods which make use of the class ID. So I gave the base class a classID field, and then I gave the derived classes Shared constructors, which I used to set the classID field to the appropriate values for each derived class. But...
45
6356
by: Ben Blank | last post by:
I'm writing a family of classes which all inherit most of their methods and code (including constructors) from a single base class. When attempting to instance one of the derived classes using parameters, I get CS1501 (no method with X arguments). Here's a simplified example which mimics the circumstances: namespace InheritError { // Random base class. public class A { protected int i;
3
2924
by: Elia Karagiannis | last post by:
The static constructor of a derived class never gets called if it has no other methods and the base class is only static I have the following base class and derived class. public class MyBase { protected MyBase() {}
8
1813
by: JAL | last post by:
According to MSDN2, if a managed class throws an exception in the constructor, the destructor will be called. If an exception is thrown in the constructor the object never existed so how in the world can the destructor of a object that does not exist get called! Here is the MSDN2 document: Code authored in Visual C++ and compiled with /clr will run a type's destructor for the following reasons: ....
74
16025
by: Zytan | last post by:
I have a struct constructor to initialize all of my private (or public readonly) fields. There still exists the default constructor that sets them all to zero. Is there a way to remove the creation of this implicit default constructor, to force the creation of a struct via my constructor only? Zytan
12
7209
by: Rahul | last post by:
Hi Everyone, I have the following code and i'm able to invoke the destructor explicitly but not the constructor. and i get a compile time error when i invoke the constructor, why is this so? class Trial { public: Trial() {
0
8996
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8832
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
9254
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...
0
8256
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6800
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
6078
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
4608
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.