473,383 Members | 1,997 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,383 software developers and data experts.

How to understand the javascript class model?

hi every one,

I have got some confused problem when I try to write some custom object
by javascript.

Look at the example code here:

<BODY>
<script language="jscript">

function Class()
{

this.member = null;
this.event = null;

this.memberFunction = function()
{
alert("memberfunc" + this.member);
this.callEvent();
alert('after call');
}

this.callEvent = function()
{
alert("call:" + this.event);
if (this.event)
{
this.event();
}
}

}

var obj = new Class();
obj.member = "hello";

obj.event = function()
{
alert('event');
}

obj.memberFunction();
</script>

<button id=hello >click</button>
<script>
hello.onclick=obj.memberFunction;
</script>

I try to define a javascript class and define a event handler for it.
There is a member and
a memberFunction and a event in the Class body. Then I created a object
(obj) of Class and
defined a event handler like this:

obj.event = function()
{
alert('event');
}

When I call the function: obj.memberFunction(); the event handler was
fired and alert
a message ('event'). But when I try to use a button to fire the event, it
doesn't work. It seems we
have lost the member function callEvent, it is a undefined value, the same
as this.event member.

Anyone can tell me why?

Aug 25 '05 #1
1 3507
On 25/08/2005 03:15, Jing You wrote:
<script language="jscript">
The language attribute has long-been deprecated in favour of the
(required) type attribute:

<script type="text/javascript">
function Class()
{

this.member = null;
this.event = null;

this.memberFunction = function()
{
alert("memberfunc" + this.member);
this.callEvent();
alert('after call');
}

this.callEvent = function()
{
alert("call:" + this.event);
if (this.event)
{
this.event();
}
}

}
In general, when all data members 'public', methods should be added via
the prototype object. This produces only one function object for each
method. With the code above, each new object will create new functions
even though they could be shared.

function Class() {
this.member = null;
this.event = null;
}
Class.prototype.memberFunction = function() {
alert('memberFunction: ' + this.member);
this.callEvent();
alert('after call');
};
Class.prototype.callEvent = function() {
alert('callEvent: ' + this.event);
if('function' == typeof this.event) {this.event();}
};

Creating methods as you did should normally be used when utilising
'private' members:

function MyObject() {
var private = 'value';

this.method = function() {
alert(private);
};
}

var o = new MyObject();

o.method(); // 'value'
o.private; // error

[snip]
<button id=hello >click</button>
<script>
hello.onclick=obj.memberFunction;
</script>
The value of id and name attributes should never be used as global
variables. Many browsers do not support this.

var element;

if(document.getElementById) {
element = document.getElementById('hello');
}
if(element) {
element.onclick = obj.memberFunction;
}
I try to define a javascript class [...]
There's no such thing. Javascript uses a prototype-based inheritance
model, where your objects use other objects as a basis for their
features and behaviours. Your Class, above, is a constructor function
that when executed, can be used to initialise an object instance and
augment the object that results from the instantiation.
When I call the function: obj.memberFunction(); the event handler was
fired and alert a message ('event'). But when I try to use a button
to fire the event, it doesn't work.


The this operator exists everywhere (unlike in other languages), and as
such, its value is determined by how code is executed.

In 'global' scope

<script type="text/javascript">
alert(this == window); // true
</script>

the this operator refers to the global object (usually referred to as
window). Similarly, functions that are called directly have the same value:

var o = {
method : function() {alert(this == window);}
},
f = o.method;

f(); // true; this refers to global object
o.method(); // false; same function object,
// but this now refers to 'o'

Notice that in this latter case, the this operator refers to the object
before the last dot operator: 'o'. A similar thing happens in your case.
When the browser fires the event listener, it does so as though it did

buttonElement.onclick()

In other words, the this operator refers to the BUTTON element.

To solve this, you need to keep a reference to the object that you can
use later. One way is to use the 'private' member form I showed earlier:

function Class() {
var instance = this;

this.member = null;
this.event = null;

this.memberFunction = function() {
alert('memberFunction: ' + instance.member);
instance.callEvent();
alert('after call');
};
}
Class.prototype.callEvent = function() {
alert('callEvent: ' + this.event);
if('function' == typeof this.event) {this.event();}
};

Looking at the implementation of the memberFunction member, you can see
that it's defined in terms of the instance private variable. Even when
the this operator will refer to the BUTTON element, instance will still
refer to the object. When the method calls the callEvent method, it does
so through the object reference, so the this operator will refer to the
object again.

Hope that helps,
Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Aug 25 '05 #2

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

Similar topics

34
by: yensao | last post by:
Hi, I have a hard time to understand difference and similarities between Relational database model and the Object-Oriented model. Can somebody help me with this? Thank you in advance. ...
4
by: annoyingmouse2002 | last post by:
Hi there, sorry if this a long post but I'm really just starting out. I've been using MSXML to parse an OWL but would like to use a different solution. Basically it reads the OWL (Based on XML)...
0
by: Leslaw Bieniasz | last post by:
Cracow, 16.09.2004 Hi, I have a problem with compiling the following construction involving cross-calls of class template methods, with additional inheritance. I want to have three class...
9
by: TCMA | last post by:
I am looking for some tools to help me understand source code of a program written in C++ by someone else. Are there any non-commercial, open source C or C++ tools to reverse engineer C or C++...
9
by: MStepansky | last post by:
Whats the difference between Javascript and Java3D? I mean can Javascript do like Java3D can? Or is Java3D on top of Javascript (the core, if thats what it is)? Then I should learn Javascript...
16
by: Brian Henry | last post by:
Is there a way to launch a javascript command from within VB code? For instance, to issue a window.open(some url) if a certain condition is met. I know you can add the javacript to a control...
4
by: Ken Nipper | last post by:
Does anyone know how to access the menu items from javascript. I can use the onclick to perform an action but I would like to be enable/disable items based on page status. Thanks Ken
104
by: Leszek | last post by:
Hi. Is it possible in javascript to operate on an array without knowing how mamy elements it has? What i want to do is sending an array to a script, and this script should add all values from...
20
by: walterbyrd | last post by:
Reading "Think Like a Computer Scientist" I am not sure I understand the way it describes the way objects work with Python. 1) Can attributes can added just anywhere? I create an object called...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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.