473,910 Members | 7,379 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Inheritance Chain

Hi everyone
Please look at the code below: (I am picking up JS from Crockfold and
a few other online sources too)

*************** *************** *************** *************** ***
function Employee(name){
this.name = name || 'default';
}

function WorkerBee(name, dept){
this.base = Employee; //Not Employee();
this.base(name) ;
this.dept = dept;
}

var test1 = new WorkerBee('test 1', 'Input/Output');

Employee.protot ype.speciality = 'none';

((test1.special ity) ? test1.specialit y : 'undefined').wr iteln(); //
returns 'undefined'

WorkerBee.proto type = new Employee;

((test1.special ity) ? test1.specialit y : 'undefined').wr iteln(); //
STILL returns 'undefined'

var test2 = new WorkerBee('test 2', 'Computer Science');

test2.specialit y.writeln(); //NOW this returns 'none'!

*************** *************** *************** *************** *************** *************** *****

My questions are follows:
1) How does the base in WorkerBee works? When I call
var test1 = new WorkerBee('test 1', 'Input/Output');
base gets assigned to Employee (as a function) and 'test1' is passed
to Employee as a parameter which return the field "name : 'test1' '"
right?
So If I were to check for the presence of a parameter named Employee
in test1 I would not find anything because what the function of
Employee merely did was pass this statement "name : 'test1' " to the
body of test1. Is this true?
(I did check test1.hasOwnPro perty(Employee) and results = false);

2) IF my understanding of prototype is true, then when I called
WorkerBee.proto type = new Employee;
this would like the function WorkerBee's prototype to an Employee
Object, and this Employee Object's prototype field is linked to
another anonymous object with the field 'speciality' = 'none'. If this
were true, how come my second call to find out the speciality of test1
STILL returned null?
Nov 14 '08 #1
6 1462
Also, I discover this while working:

//Following the code above;
function WorkerCee(name, dept){
Employee.call(t his, name);
this.dept = dept || '';
}

var Vincent = new WorkerCee('Vinc ent', 'Morgan-Stanley');
Why does the variable Vincent not have the field speciality EVEN after
employee.protot ype.speciality has been declared 'none'??

Nov 14 '08 #2
How does the base in WorkerBee work?

When a new WorkerBee object is created, the following happens,
see 15.3.5.2 of the ECMA-262 Standard:

(a) the script engine makes a new object.
(b) the engine assigns the current value of the 'prototype' property
of the WorkerBee constructor, which at this point is some
'anonymous' object, to the internal [[prototype]] property of the
new object.
(c) the engine calls the WorkerBee function passing the newly
created object as the current value of the 'this' variable.
(d) the WorkerBee function assigns the Employee function as a value
to the 'base' property of the new object.
(e) the WorkerBee function uses the expression 'this.base()'
to call the Employee function with the new object as the
current value of the 'this' variable inside Employee, too.
(f) the Employee function assigns the value of the given 'name'
parameter to the 'name' property of the new object
and returns.
(g) the WorkerBee function finishes by storing the value of
the given 'dept' parameter in the 'dept' property
of the new object.
(h) the WorkerBee function returns the new object to the engine
which assigns it as a reference to the test1 variable.
So If I were to check for the presence of a parameter named Employee
in test1 I would not find anything because what the function of
Employee merely did was pass this statement "name : 'test1' " to the
body of test1. Is this true?
(I did check test1.hasOwnPro perty(Employee) and results = false);
Yes!
test1.hasOwnPro perty("Employee ")==false

But!
test1.hasOwnPro perty("base")== true

It would be good practice to include the statement "delete this.base"
in WorkerBee to avoid that situation.
... how come my second call to find out the speciality of test1
STILL returned null?
Because the internal [[prototype]] property of an existing object is
NOT
updated when the value of the 'prototype' property of its constructor
function changes.
When you create test2, that changed prototype is used, however, and
is responsible to give the result 'none'.

Hubert

Nov 14 '08 #3
Ok so let me get this straight...(Thi s is a little hard to explain in
words..)...

1) Whenever you call a constructor, the engine creates an anonymous
object and assigns the value of its parameter to that anonymous
object, but then that object's __proto__ field is assigned the value
of the Constructors' prototype right?

2) When I call another constructor within a constructor, do I also
create ANOTHER ANONYMOUS OBJECT by the method of 1) above?

So in this illustration,
fn_WorkerBee.pr ototype---->anonymous_obje ct.__proto__ where
anonymous_objec t.base------>another_anonym ous_object created by
Employee's constructor?

3)
"
Because the internal [[prototype]] property of an existing object is
NOT
updated when the value of the 'prototype' property of its constructor
function changes.
When you create test2, that changed prototype is used, however, and
is responsible to give the result 'none'.
"

If i were to indicate the direction of the link with the arrow,
does this mean

fn_workerbee.pr ototype---->my_Object.__pr oto__
hence if fn_workerbee.pr ototype gets any changes my_Object will not be
able to detect since it is in the reverse side of the inheritance
chain

but like what you said, shouldn't the function workerbee have access
to the my_object since fn_workerbee.pr ototype is directly linked to my
object?

Does this mean that every object created is linked to their
constructor?
Nov 14 '08 #4
disappearedng <di***********@ gmail.comwrites :
Ok so let me get this straight...(Thi s is a little hard to explain in
words..)...

1) Whenever you call a constructor, the engine creates an anonymous
object and assigns the value of its parameter to that anonymous
object, but then that object's __proto__ field is assigned the value
of the Constructors' prototype right?
Only if you call the constructor using the <<new Constructor>or <<new
Constructor(... )>statements. Otherwise it works just like a normal
method/function call and no new object is created at all. Also, I'm
assuming you mean it set's <<this>to the newly created object.
2) When I call another constructor within a constructor, do I also
create ANOTHER ANONYMOUS OBJECT by the method of 1) above?
Depends on how you call it: see above.

[ ... lots of stuff snipped ... ]
Does this mean that every object created is linked to their
constructor?
No. Every object has a [[prototype]] that may or may not refer to its
constructor.

I tried to explain most of this some time ago:

http://joost.zeekat.nl/constructors-...confusing.html

--
Joost Diepenmaat | blog: http://joost.zeekat.nl/ | work: http://zeekat.nl/
Nov 14 '08 #5
vw*******@gmail .com wrote:
Please look at the code below: (I am picking up JS from Crockfold and
a few other online sources too)
It would appear you picked up the bad examples.
*************** *************** *************** *************** ***
function Employee(name){
this.name = name || 'default';
}

function WorkerBee(name, dept){
this.base = Employee; //Not Employee();
this.base(name) ;
Another, less compatible possibility is

Employee.call(t his, name);
this.dept = dept;
}

var test1 = new WorkerBee('test 1', 'Input/Output');

Employee.protot ype.speciality = 'none';

((test1.special ity) ? test1.specialit y : 'undefined').wr iteln(); //
returns 'undefined'

WorkerBee.proto type = new Employee;
This inheritance pattern, which unfortunately originates from the first
versions of Netscape JavaScript References and has survived in numerous
tutorials to date (even the Wikipedia article), is essentially a wrong
one, meaning that it does not do what it is intended to do.

It does *not* insert the prototype object of `Employee'[1],
`Employee.proto type', in the prototype chain of `Workerbee' objects so that
`Workerbee' objects would inherit from `Employee.proto type':

A: (new WorkerBee) --WorkerBee.proto type --Employee.protot ype

Instead, it inserts a new `Employee' object in the prototype chain so that
`WorkerBee' objects inherit from that:

B: (new WorkerBee) --new Employee --Employee.protot ype

That little thing makes a big difference when the `Employee' constructor
adds properties to the object or modifies prototype properties, as here,
because the lookup algorithm finds the dynamically added properties of
*the same object* first.

Unless you need behavior B, use the following pattern to achieve A instead:

function inheritFrom(Con structor)
{
function Dummy() {}
Dummy.prototype = Constructor.pro totype;
return new Dummy();
}

WorkerBee.proto type = inheritFrom(Emp loyee);

The result is the following prototype chain:

A2: (new WorkerBee) --WorkerBee.proto type --(new Dummy)
--Employee.protot ype

Since `Dummy' objects have no properties of their own, they don't interfere
with the property lookup.

NOTE: This isn't exactly news around here.
((test1.special ity) ? test1.specialit y : 'undefined').wr iteln(); //
STILL returns 'undefined'
It's inefficient and harder to maintain to begin with. Consider this instead:

(test1.speciali ty || 'undefined').wr iteln();

But since when has a String object (that the primitive string value is being
converted to here) a writeln() method? Maybe you were looking for

document.writel n(test1.special ity || 'undefined');

BTW: Maybe I'm wrong, but I think the word should be "specialty" .
var test2 = new WorkerBee('test 2', 'Computer Science');

test2.specialit y.writeln(); //NOW this returns 'none'!
^^^^^^^^^^^^^^^ ^^^^^
If this really works chances are you are using some kind of framework that
augments the `String.prototy pe' object, so all bets are off until you post
the (*stripped-down*) code of that method. By default (per Specification)
String objects do not have or inherit a writeln() method.
*************** *************** *************** *************** *************** *************** *****

My questions are follows:
1) How does the base in WorkerBee works? When I call
var test1 = new WorkerBee('test 1', 'Input/Output');
base gets assigned to Employee (as a function) and 'test1' is passed
to Employee as a parameter which return the field "name : 'test1' '"
right?
No. In a constructor, `this' refers to the object that is being constructed
with it; not to the constructor itself. So the newly created `Employee'
object is augmented with a `base' property that is called afterwards.
So If I were to check for the presence of a parameter named Employee
in test1 I would not find anything
Correct aside from the use of the term "parameter" . You mean a *property*.
because what the function of
Employee merely did was pass this statement "name : 'test1' " to the
body of test1. Is this true?
No. Although this has been explained here ad nauseam before --

<http://jibbering.com/faq/#posting>

--, why not use a debugger to find it out for yourself?

<http://jibbering.com/faq/#debugging>
(I did check test1.hasOwnPro perty(Employee) and results = false);
Works as designed. `Employee' is a reference to a Function object.
Object.prototyp e.hasOwnPropert y() expects (of course) as *string value* to
contain the property *name*. If the argument was not of type string, it
would be converted to string. The string representation of `Employee' is
something along "function Employee(...) {\n ...\n}", and there is no
property with *that* name.

But even if you passed "Employee", the method would return `false', for the
reason explained above.
2) IF my understanding of prototype is true, then when I called
WorkerBee.proto type = new Employee;
this would like the function WorkerBee's prototype to an Employee
Object, and this Employee Object's prototype field is linked to
another anonymous object with the field 'speciality' = 'none'.
Roughly speaking that's correct. However, you need to use proper terms: In
ECMAScript implementations , objects have *properties*, not fields. Objects
are *being referred to* (with *references* that are values, and properties
to hold those values), not being linked.
If this were true, how come my second call to find out the speciality
of test1 STILL returned null?
Impossible to say. A `TypeError' exception should have been thrown
("test2.special ity.writeln is not a function"). Either your framework
has interfered, like

String.prototyp e.writeln = function() {
document.write( this);
};

or you don't post exactly the code that you are using, or you are not
testing nearly as thorough as you think.
HTH

PointedEars
___________
[1] For the sake of brevity I am referring to identifiers as objects, even
though they only represent references to objects of which there can be
more than one.
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f8************ *******@news.de mon.co.uk>
Nov 14 '08 #6
disappearedng wrote:
1) Whenever you call a constructor, the engine creates an anonymous
object and assigns the value of its parameter to that anonymous
object, but then that object's __proto__ field is assigned the value
of the Constructors' prototype right?
No. The object is augmented with a `__proto__' *property* with that value
*in (Netscape/Mozilla.org) JavaScript* (so not in Microsoft JScript and
other incompatible implementations ).
2) When I call another constructor within a constructor, do I also
create ANOTHER ANONYMOUS OBJECT by the method of 1) above?
No.
So in this illustration,
fn_WorkerBee.pr ototype---->anonymous_obje ct.__proto__ where
anonymous_objec t.base------>another_anonym ous_object created by
Employee's constructor?
Please restate your request.
3)
"
Because the internal [[prototype]] property of an existing object is
NOT
updated when the value of the 'prototype' property of its constructor
function changes.
When you create test2, that changed prototype is used, however, and
is responsible to give the result 'none'.
"
That's not the reason why. The internal [[prototype]] property does not
need to be updated then without the prototype chain to break, if the latter
has been set up properly in the first place. What properties an object
effectively has (meaning provides as it owns and inherits them) is
determined *on lookup*, not before.
If i were to indicate the direction of the link with the arrow,
There is no link.
does this mean

fn_workerbee.pr ototype---->my_Object.__pr oto__
No.
hence if fn_workerbee.pr ototype gets any changes my_Object will not be
able to detect since it is in the reverse side of the inheritance
chain
Again, only if the prototype chain was set up that way (not properly).
but like what you said, shouldn't the function workerbee have access
to the my_object since fn_workerbee.pr ototype is directly linked to my
object?
Please restate your request.
Does this mean that every object created is linked to their
constructor?
No.
PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm>
Nov 14 '08 #7

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

Similar topics

5
2131
by: Jeff Greenberg | last post by:
Not an experienced c++ programmer here and I've gotten myself a bit stuck. I'm trying to implement a class lib and I've run into a sticky problem that I can't solve. I'd appreciate any help that I can get! Consider 3 classes in the following heirarchy: base / \ deriv1 deriv2 \
3
3382
by: santosh | last post by:
Hi All , Why does the below code doesn't compile?? class Interface { public: virtual void funA() = 0; virtual void funB() = 0; virtual void funD() = 0; Interface();
7
12884
by: Hazz | last post by:
Are there any good references/articles/books which provide clarity toward my insecurity still on deciding how to model a complex system? I still feel uncomfortable with my understanding, even though I have worked with these systems on when to decide to use interfaces (and how they should be developed) as opposed to or complemented by the use of inheritance from base classes. If I am thinking from the point of view of some specific activity...
31
1965
by: John W. Kennedy | last post by:
I quite understand about prototypes and not having classes as such, but I happen to have a problem involving blatant is-a relationships, such that inheritance is the bloody obvious way to go. I can think of several ad-hoc ways to achieve inheritance, but is there an accepted standard idiom? -- John W. Kennedy "But now is a new thing which is very old-- that the rich make themselves richer and not poorer, which is the true Gospel, for...
6
1493
by: mmcloughlin | last post by:
I'm learning about objects and am trying to figure out how basic inheritance works. I've got into the habit of explicitly setting the prototype object with an object literal as it seems to make the creation of a class easier to read/understand. Anyway it seems to break the inheritance chain in the following code and I don't know why. window.onload = function() {
36
2750
by: Pacific Fox | last post by:
Hi all, haven't posted to this group before, but got an issue I can't work out... and hoping to get some help here ;-) I've got a base object that works fine with named arguments when called on it's own. However when I call the child object I get an error " has no properties (in firefox)." I simple test:
22
9914
by: Fabio Z | last post by:
Hi all, I have a classic problem: List<Tand List<Xwhere X is a class X : T. Ok, I know the problem: I cannot cast List<Ton List<Xbecause also if X is a T, List<Xis not a List<T>. What I don't know is the solution :) Let's see this scenario (that obviously doesn't compile): // -------------------------- class BaseClass
6
1890
by: burningodzilla | last post by:
Hi all - I'm preparing to dive in to more complex application development using javascript, and among other things, I'm having a hard time wrapping my head around an issues regarding "inheritance" using the prototype property. I realize there are no classes in JS, that code therefore lives in objects instead of class definitions, and that "inheritance" must be achieved prototypically and not classically. That said, on with the code. Say I...
2
2105
by: beseecher | last post by:
Hi, In my research in the javascript language I have encountered problems with implementing prototype inheritance while preserving private methods functioning properly. Here is an example: function A(){ var _this = this; this.a = 10;
0
10037
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
9879
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,...
1
11055
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
10541
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
9727
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...
0
5939
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...
1
4776
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
2
4337
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3360
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.