473,385 Members | 1,869 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

confusion while understanding prototype

VJ
I tried to write sample code to get understanding of javascript's
prototypal inheritance (along with the variety of function calling
choices.. )

During the process, I got myself throughly confused.

Can anyone explain following behavior [NOTE: Needs firefox+firebug.
otherwise replace all console.* to alert or equivalent]

here is my code:
<html>
<head>
<script type="text/javascript">

function MyClass(){
if(String(this) == '[object Window]'){
console.debug('Are you sure to use this object in global scope?? Or
you just missed using \'new\' keyword?');
}
this.method = function(){
console.info('in MyClass.method');
}
this.param1='param1';
}

function caller(){
var execClsDirectly = MyClass();
var execClsConstructor = new MyClass();

// execClsDirectly would be null since MyClass does not have any
return statement
if (execClsDirectly) execClsDirectly.param2='added global fn call';

execClsConstructor.param2='added to obj instance';

var clsRef = MyClass;
clsRef.param2='added to class definition';

MyClass.prototype.param2='added to class';

console.log('execClsConstructor param2: '+execClsConstructor.param2);
console.log('outer param2: '+MyClass.param2);

var updatedClsConstructor = new MyClass();
console.log('updatedClsConstructor param2:
'+updatedClsConstructor.param2);

}
</script>
</head>
<body onload="caller();">
</body>
</html>

the output:
Are you sure to use this object in global scope?? Or you just missed
using 'new' keyword?
execClsConstructor param2: added to obj instance
outer param2: added to class definition
updatedClsConstructor param2: added to class
I of course understand the first line of output, but.. confused as to
same param2 added into MyClass gets added into three different levels.

Can anyone elaborate this?
Hope I was able to articulate my confusion in words...

Regards,
VJ

Oct 4 '07 #1
2 1280
VJ wrote:
I tried to write sample code to get understanding of javascript's
prototypal inheritance (along with the variety of function calling
choices.. )

During the process, I got myself throughly confused.

Can anyone explain following behavior [NOTE: Needs firefox+firebug.
otherwise replace all console.* to alert or equivalent]

here is my code:
<html>
<head>
<script type="text/javascript">

function MyClass(){
if(String(this) == '[object Window]'){
I think a safer test here would be:

if (this == window) {

console.debug('Are you sure to use this object in global scope?? Or
you just missed using \'new\' keyword?');
}
this.method = function(){
console.info('in MyClass.method');
}
this.param1='param1';
}

function caller(){
var execClsDirectly = MyClass();
A.
var execClsConstructor = new MyClass();

// execClsDirectly would be null since MyClass does not have any
return statement
if (execClsDirectly) execClsDirectly.param2='added global fn call';

execClsConstructor.param2='added to obj instance';
B.
>
var clsRef = MyClass;
clsRef.param2='added to class definition';
C.
>
MyClass.prototype.param2='added to class';
D.
>
console.log('execClsConstructor param2: '+execClsConstructor.param2);
console.log('outer param2: '+MyClass.param2);

var updatedClsConstructor = new MyClass();
console.log('updatedClsConstructor param2:
'+updatedClsConstructor.param2);

}
</script>
</head>
<body onload="caller();">
</body>
</html>

the output:
Are you sure to use this object in global scope?? Or you just missed
using 'new' keyword?
You understand why this does what it does - good. See A.

execClsConstructor param2: added to obj instance
Because you added a property called param2 to the execClsConstructor
object and assigned it a value of 'added to obj instance'. See B.

outer param2: added to class definition
Because you created a variable clsRef and assigned a value that is a
reference to the MyClass function object. You then added a param2
property and assigned it a value of 'added to class definition'. See C.

You may as well have written:

MyClass.param2 = 'added to class definition';

There are no classes in javascript 1.5 (ECMAScript Language Ed. 3).
MyClass is a function object, it is not a 'class'. *Any* function
object called with the new operator acts like a constructor.

When a function is called with the new operator:

- a new object is created
- the function's this keyword is assigned a reference to the new object
- the new object's prototype property is assigned a reference to the
constructor's prototype object
- the new object is returned at the completion of the function unless
you return some other object or value.

Other stuff happens too, but the above is the important bit for now.

Note that the constructor itself is not on the inheritance chain, the
new object gets the properties explicitly assigned, e.g.:

this.param1 = 'param1';

plus whatever is on the prototype chain is available as if it were on
the object itself (more or less).

updatedClsConstructor param2: added to class
Because you added a param2 property to MyClass.prototype, which is on
the protoype chain for objects created using MyClass as a constructor.
See D.

For example:

function Foo(){
this.param1 = 'param1';
}

var f0 = new Foo();
alert(f0.param1); // shows param1

Foo.prototype.param2 = 'param2';
alert(f0.param2); // shows param2
That's how *prototype* based inheritance works - via the prototype
chain. :-)

I of course understand the first line of output, but.. confused as to
same param2 added into MyClass gets added into three different levels.

Can anyone elaborate this?
I hope I did.

--
Rob
"We shall not cease from exploration, and the end of all our
exploring will be to arrive where we started and know the
place for the first time." -- T. S. Eliot
Oct 4 '07 #2
RobG wrote:
VJ wrote:
><script type="text/javascript">
var _global = this;
>function MyClass(){
if(String(this) == '[object Window]'){

I think a safer test here would be:

if (this == window) {
And

if (this == _global) {

would be safest.
> console.debug('Are you sure to use this object in global scope?? Or
you just missed using \'new\' keyword?');
}
[...]

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>
Oct 4 '07 #3

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

Similar topics

8
by: Roman Töngi | last post by:
I don't yet understand how to divide a C++ project into header and implementation files. The following won't compile: // Apple.cpp #include <iostream> #include "random.h" using namespace std;...
9
by: Mac A. Cody | last post by:
Hello, I'm encountering a problem with using stdarg that I cannot figure out. I'm trying to develop a function for a linux driver module that takes a variable-length sequence of u8-type...
3
by: Ken Varn | last post by:
I have Page1 that does a transfer to page2. When the user is done with Page2, there is a button on Page2 that they can press to bring them back to Page1. I use Server.Transfer to navigate from...
39
by: Martin Jřrgensen | last post by:
Hi, I'm relatively new with C-programming and even though I've read about pointers and arrays many times, it's a topic that is a little confusing to me - at least at this moment: ---- 1)...
3
by: Beta What | last post by:
Hello, I have a question about casting a function pointer. Say I want to make a generic module (say some ADT implementation) that requires a function pointer from the 'actual/other modules'...
6
by: Bryan | last post by:
Lets say I have a form From1, and I add a text box to it, TextBox1, in the VS2005 form designer. I set the 'Text' property of TextBox1 to "Original" using the properties dialog box in the form...
18
by: william | last post by:
below is a short piece of code I wrote to testify my understanding of char *, and array. #include <stdio.h> int main() { char *str=NULL; char x="today is good!"; printf("%s", str);
12
sumittyagi
by: sumittyagi | last post by:
Hi everybody! I am having a difficulty in understanding the prototype pattern. Actually I got the idea behind it, but the example given in wikipedia for this pattern have confused me. The code is...
8
by: vaib | last post by:
hi all , It really seems that C never ceases to amaze . All this time i've been doing C and i thought i was quite adept at it but i was wrong . So without wasting any more time , here's the...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.