473,748 Members | 2,274 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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('i n MyClass.method' );
}
this.param1='pa ram1';
}

function caller(){
var execClsDirectly = MyClass();
var execClsConstruc tor = new MyClass();

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

execClsConstruc tor.param2='add ed to obj instance';

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

MyClass.prototy pe.param2='adde d to class';

console.log('ex ecClsConstructo r param2: '+execClsConstr uctor.param2);
console.log('ou ter param2: '+MyClass.param 2);

var updatedClsConst ructor = new MyClass();
console.log('up datedClsConstru ctor param2:
'+updatedClsCon structor.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?
execClsConstruc tor param2: added to obj instance
outer param2: added to class definition
updatedClsConst ructor 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 1303
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('i n MyClass.method' );
}
this.param1='pa ram1';
}

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

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

execClsConstruc tor.param2='add ed to obj instance';
B.
>
var clsRef = MyClass;
clsRef.param2=' added to class definition';
C.
>
MyClass.prototy pe.param2='adde d to class';
D.
>
console.log('ex ecClsConstructo r param2: '+execClsConstr uctor.param2);
console.log('ou ter param2: '+MyClass.param 2);

var updatedClsConst ructor = new MyClass();
console.log('up datedClsConstru ctor param2:
'+updatedClsCon structor.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.

execClsConstruc tor param2: added to obj instance
Because you added a property called param2 to the execClsConstruc tor
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).

updatedClsConst ructor param2: added to class
Because you added a param2 property to MyClass.prototy pe, 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.p aram2 = '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
1928
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; int main() {
9
1829
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 values. Below is the function: #include <stdarg.h> .. ..
3
1555
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 one page to the next. The confusion that I am having is that when the user is done with Page2 and clicks on the button to bring them back to Page1, I want Page1 to basically come back with the exact same view that it had before the user navigated...
39
19646
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) What's the difference between these 3 statements: (i) memcpy(&b, &KoefD, n); // this works somewhere in my code
3
3653
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' that takes arguments of type (void *) because the ADT must be able to deal with any type of data. In my actual code, I will code the function to take arguments of their real types, then when I pass this pointer through an interface function, I...
6
1060
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 designer. Consider the following code that runs on the loading of the form dim txt as new TextBox txt.Text = "changed" Me.TextBox1 = txt I was thinking that when I open the form the text in the textbox would
18
605
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
3027
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 as follows. /** Prototype Class **/ public class Cookie implements Cloneable { public Object clone() {
8
2389
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 confusion . I read in K&R that ANSI introduced the concept of function prototyping in C and it was missing there initially ( it borrowed the concept from C++ ) _but_ it did it make it compulsory to actually include the function declaration in the...
0
8991
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
8831
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
9552
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9376
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...
0
8245
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
6796
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
6076
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
4607
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...
3
2215
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.