473,545 Members | 721 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can you recommend a tutorial on using objects in javascript?

Can anyone recommend a good online guide to using objects in javascript?
The book I bought (DHTML Utopia) suggests using objects to keep the code
clean and stop namespace clashes between different parts of the code, but
as far as I can see, the way objects work in javascript is quite awkward.
I had it working the way they suggest in the book, and it was going OK
until I wanted to call one object method from another - I couldn't find a
syntax for this that worked. I tried following a guide I found online, and
the way they say to do it means putting 'this.' before practically
everything, and the code still doesn't work. I'm tempted just to forget
about objects and do the whole thing as separate functions, but I still
don't quite want to do this.

please help!

--
http://www.niftybits.ukfsn.org/

remove 'n-u-l-l' to email me. html mail or attachments will go in the spam
bin unless notified with [html] or [attachment] in the subject line.

May 23 '06 #1
13 2080
Andy Baxter wrote:
Can anyone recommend a good online guide to using objects in
javascript?
Since everything in javascript is an object, pretty much doing _anything_
involves using objects :)
The book I bought (DHTML Utopia) suggests using objects
to keep the code clean and stop namespace clashes between different
parts of the code, but as far as I can see, the way objects work in
javascript is quite awkward.
"Different than most people are used to" != awkward.
Once you get used to it, it's easily understood.

Using objects as a "namespace" to encapsulate functions is a good idea.

A simple example:

var MyLib = {};
MyLib.funcA = function() { ... }
myLib.funcB = function() { ... }
I had it working the way they suggest in
the book
What did they suggest?
and it was going OK until I wanted to call one object
method from another - I couldn't find a syntax for this that worked.
Depends on exactly what kind of syntax you were using.

For example:

var MyLib2 = {};
MyLib2.funcC = function() { MyLib.funcA(); }
I tried following a guide I found online, and the way they say to do
it means putting 'this.' before practically everything, and the code
still doesn't work.
Using "this" only applies to instantiated objects. If you're only using
objects as a namespace, then you won't be instantiating them and won't have
any use for 'this'.
I'm tempted just to forget about objects and do
the whole thing as separate functions, but I still don't quite want
to do this.


Depending on exactly what you're doing, this may not be a bad thing. Global
functions are not evil, especially if you have full control of the page. If
you are building reusable code, however, encapsulating functionality into a
namespace is a good idea.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
May 23 '06 #2
Matt Kruse said:
Andy Baxter wrote:
and it was going OK until I wanted to call one object
method from another - I couldn't find a syntax for this that worked.


Depends on exactly what kind of syntax you were using.

For example:

var MyLib2 = {};
MyLib2.funcC = function() { MyLib.funcA(); }


In the code below, the line I've marked doesn't work - it never reaches
the pano.moveImages () function. If I change it to just 'moveImages;'
(which is what I tried first), it gives an error: 'moveImages is not
defined'. I'm confused about this, because referring to object properties
like mouseDown and pan from inside the functions works fine without adding
'pano.' in front, but referring to one of the object methods doesn't. If
you have any general comments on the way I've written this, I'd appreciate
that too, as this is the first program I've written in javascript.

// Panorama script
// By Andy Baxter, May 2006

function showMessage(str ) {
var rep=document.ge tElementById("m essage1");
rep.innerHTML=s tr;
}

function showMessage2(st r) {
var rep=document.ge tElementById("m essage2");
rep.innerHTML=s tr;
}
var pano = {
// initialisation for the panorama.
// pixels to move when mouse is at full left / right.
scale: 0,
// mouse status.
mouseDown: 0,
mouseX: 0,
mouseY: 0,
// ratio that panorama is panned to left.
pan: 0,
// size of pano image [width,height]
imgSize: 0,
scaledImgSize: 0,
// references to DOM objects.
panoDiv: 0,
panoPic1: 0,
init: function() {
// initialise variables;
scale=30;
mouseDown=0;
mouseX=0;
mouseY=0;
pan=0;
panoDiv = document.getEle mentById("panoD iv");
panoPic1 = document.getEle mentById("panoI mage1");
panoPic2 = document.getEle mentById("panoI mage2");
imgSize=new Array(2);
imgSize[0]=3996;
imgSize[1]=500;
var imgScale=parseI nt(panoDiv.styl e.height)/imgSize[1];
scaledImgSize=n ew Array(2);
scaledImgSize[0]=imgScale*imgSi ze[0];
scaledImgSize[1]=imgScale*imgSi ze[1];
panoPic1.style. width=scaledImg Size[0]+"px";
panoPic1.style. height=scaledIm gSize[1]+"px";
panoPic2.style. width=scaledImg Size[0]+"px";
panoPic2.style. height=scaledIm gSize[1]+"px";
// connect events.
dojo.event.conn ect(panoDiv, "onmousedow n", pano, "onMouseDow n");
dojo.event.conn ect(panoDiv, "onmouseup" , pano, "onMouseUp" );
dojo.event.conn ect(panoDiv, "onmousemov e", pano, "onMouseMov e");
dojo.event.conn ect(panoPic1, "onmousemov e", pano, "stopdefaul t");
dojo.event.conn ect(panoPic1, "onmousedow n", pano, "stopdefaul t");
dojo.event.conn ect(panoPic1, "onmouseup" , pano, "stopdefaul t");
dojo.event.conn ect(panoPic1, "onmousecli ck", pano, "stopdefaul t");
setInterval( pano.mover ,100);
},
mover: function() {
var d=new Date();
showMessage("mo useX: "+mouseX+" mouseY: "+mouseY+" mousedown:"+mou seDown+" secs:"+d.getSec onds());
// called every so often to move the panorama.
if (! mouseDown) return;
var width=parseInt( panoDiv.style.w idth);
// work out how much to move based on position in the viewport.
var offset=-Math.round(scal e*2*((mouseX-width/2)/width));
pan -= offset/scaledImgSize[0];
if (pan <0) {
pan +=1;
}
else if (pan >1) {
pan -=1;
}
**** next line doesn't work *****
pano.moveImages ;
//panoPic1.style. left="-"+(pan * scaledImgSize[0])+"px";
//panoPic2.style. left=((-pan*scaledImgSi ze[0])+scaledImgSize[0])+"px";
},
clipImage: function(img) {
// clip an image to make it fit in the viewport.
var pos=parseInt(im g.style.left);
var width=parseInt( img.style.width );
var divWidth=parseI nt(panoDiv.styl e.width);
var leftClip, rightClip;
// clip off the left side if the image crosses the left edge of the viewport.
leftClip=(pos<0 )?-pos:0;
// and the same for the right side.
rightClip=(pos+ width>divWidth) ?pos+divWidth:w idth;
img.style.clip= "rect(0px,"+rig htClip+"px,"+pa noDiv.style.hei ght+","+leftCli p+"px)";
},
moveImages: function() {
// move images to a position depending on the pan value.
alert(here);
showMessage2("o ffset: "+offset+" pic x:"+panoPic1.st yle.left+" pan:"+pan);
panoPic1.style. left="-"+(pan * scaledImgSize[0])+"px";
panoPic2.style. left=((-pan*scaledImgSi ze[0])+scaledImgSize[0])+"px";
// clip the images according to where they are in the viewport.
//this.clipImage( panoPic1);
//this.clipImage( panoPic2);
},
stopDefault: function(evt) {
evt.preventDefa ult;
},
onMouseDown: function(evt) {
mouseDown=-1;
evt.stopPropaga tion;
evt.preventDefa ult;
},
onMouseUp: function(evt) {
mouseDown=0;
evt.stopPropaga tion;
evt.preventDefa ult;
},
onMouseMove: function(evt) {
// update the mouse coords.
mouseX=evt.clie ntX-dojo.style.getT otalOffset(pano Div,"left",0);
mouseY=evt.clie ntY-dojo.style.getT otalOffset(pano Div,"top",0);
evt.stopPropaga tion;
evt.preventDefa ult;

}
}

dojo.addOnLoad( pano.init);

**** HTML file follows ****

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"> <html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Panora ma-test</title>
<script type="text/javascript" src="js/dojo/dojo.js"></script> <script
type="text/javascript" src="js/pano.js"></script>
</head>
<body>
<h1 id="heading">Pa norama Test
</h1>
<p id="message1">& nbsp;</p>
<p id="message2">& nbsp;</p>
<div style="position : relative; top: 0px; left: 0px;"> <div id="panoDiv"
style="position : absolute; top: 0px; left: 30px; width: 700px; height:
400px; clip: rect(0px, 700px, 400px, 0px);"><img id="panoImage1 "
style="position : absolute; width: auto; height: 400px; left: 0px;
z-index: 10;" alt="" src="pano2.jpg" ><img id="panoImage2 "
style="position : absolute; width: auto; height: 400px; left: 0px;
z-index: 9;" alt="" src="pano2.jpg" ></div>
</div>
<p>&nbsp;</p>
</body>
</html>


--
http://www.niftybits.ukfsn.org/

remove 'n-u-l-l' to email me. html mail or attachments will go in the spam
bin unless notified with [html] or [attachment] in the subject line.

May 23 '06 #3
Andy Baxter wrote:
Matt Kruse said:
Andy Baxter wrote:
and it was going OK until I wanted to call one object
method from another - I couldn't find a syntax for this that worked. Depends on exactly what kind of syntax you were using.

For example:

var MyLib2 = {};
MyLib2.funcC = function() { MyLib.funcA(); }


In the code below, the line I've marked doesn't work - it never reaches
the pano.moveImages () function. If I change it to just 'moveImages;'
(which is what I tried first), it gives an error: 'moveImages is not
defined'. I'm confused about this, because referring to object properties
like mouseDown and pan from inside the functions works fine without adding
'pano.' in front, but referring to one of the object methods doesn't. If
you have any general comments on the way I've written this, I'd appreciate
that too, as this is the first program I've written in javascript.

// Panorama script
// By Andy Baxter, May 2006

function showMessage(str ) {
var rep=document.ge tElementById("m essage1");
rep.innerHTML=s tr;
}


Don't post code with tabs, use 2 or 4 spaces for indentation.

[...]
var pano = {
// initialisation for the panorama.
// pixels to move when mouse is at full left / right.
scale: 0,
// mouse status.
mouseDown: 0,
mouseX: 0,
mouseY: 0,
// ratio that panorama is panned to left.
pan: 0,
// size of pano image [width,height]
imgSize: 0,
scaledImgSize: 0,
// references to DOM objects.
panoDiv: 0,
panoPic1: 0,
init: function() {
You might find it easier to add methods using:

pano.init = function()
{
// function body
}
// initialise variables;
scale=30;
mouseDown=0;
mouseX=0;
mouseY=0;
pan=0;

You must be very careful with creating variables this way. Omitting
'var' means that before pano.init() is called, they are all undefined.
After pano.init() is called, they are all global variables. Perhaps
they should be properties of pano?

panoDiv = document.getEle mentById("panoD iv");
panoPic1 = document.getEle mentById("panoI mage1");
panoPic2 = document.getEle mentById("panoI mage2");
Some feature detection for getElementById before attempting to use it
would be good, particularly inside an init function. If it's not
supported, deal with it before going any further.

imgSize=new Array(2);
imgSize[0]=3996;
imgSize[1]=500;
You can initialise the array as:

imgSize = [3996, 500];
[...] // connect events.
dojo.event.conn ect(panoDiv, "onmousedow n", pano, "onMouseDow n"); [...] dojo.event.conn ect(panoPic1, "onmousecli ck", pano, "stopdefaul t");
You didn't inlcude the dojo library, so lots of errors thrown here...

[...]
} **** next line doesn't work *****
pano.moveImages ;


If you want to call pano.moveImages , use '()':

pano.moveImages ();

The above line just returns a reference to the function and does nothing
with it. It would make more sense to place the call after the function
declaration.

[...]
--
Rob
Group FAQ: <URL:http://www.jibbering.c om/faq/>
May 24 '06 #4

Andy Baxter wrote:
Can anyone recommend a good online guide to using objects in javascript?
The book I bought (DHTML Utopia) suggests using objects to keep the code
clean and stop namespace clashes between different parts of the code, but
as far as I can see, the way objects work in javascript is quite awkward.
I had it working the way they suggest in the book, and it was going OK
until I wanted to call one object method from another - I couldn't find a
syntax for this that worked. I tried following a guide I found online, and
the way they say to do it means putting 'this.' before practically
everything, and the code still doesn't work. I'm tempted just to forget
about objects and do the whole thing as separate functions, but I still
don't quite want to do this.

If you are looking for class-based inheritance you can simulate it.

http://www.kevlindev.com/tutorials/j...ance/index.htm

Here is something I haven't studied yet

http://www.crockford.com/javascript/inheritance.html

- Peter

May 24 '06 #5
RobG said:
Andy Baxter wrote:
// Panorama script
// By Andy Baxter, May 2006

function showMessage(str ) {
var rep=document.ge tElementById("m essage1");
rep.innerHTML=s tr;
}
Don't post code with tabs, use 2 or 4 spaces for indentation.

[...]
var pano = {
// initialisation for the panorama.
// pixels to move when mouse is at full left / right.
scale: 0,
// mouse status.
mouseDown: 0,
mouseX: 0,
mouseY: 0,
// ratio that panorama is panned to left.
pan: 0,
// size of pano image [width,height]
imgSize: 0,
scaledImgSize: 0,
// references to DOM objects.
panoDiv: 0,
panoPic1: 0,
init: function() {


You might find it easier to add methods using:

pano.init = function()
{
// function body
}


I liked that syntax because it's clearer and everything is wrapped up in
the same chunk.
// initialise variables;
scale=30;
mouseDown=0;
mouseX=0;
mouseY=0;
pan=0;

You must be very careful with creating variables this way. Omitting
'var' means that before pano.init() is called, they are all undefined.
After pano.init() is called, they are all global variables. Perhaps
they should be properties of pano?


I thought they were - I was assuming that once I'd declared them as
properties of pano, then after that I could refer to them as such without
the 'var'. I think I'm still thinking javascript is like C++ when it
isn't.
panoDiv = document.getEle mentById("panoD iv"); panoPic1 =
document.getEle mentById("panoI mage1"); panoPic2 =
document.getEle mentById("panoI mage2");


Some feature detection for getElementById before attempting to use it
would be good, particularly inside an init function. If it's not
supported, deal with it before going any further.


OK.
imgSize=new Array(2);
imgSize[0]=3996;
imgSize[1]=500;


You can initialise the array as:

imgSize = [3996, 500];


OK.
[...]
// connect events.
dojo.event.conn ect(panoDiv, "onmousedow n", pano, "onMouseDow n");

[...]
dojo.event.conn ect(panoPic1, "onmousecli ck", pano, "stopdefaul t");


You didn't inlcude the dojo library, so lots of errors thrown here...


It's included in the html file.

}
**** next line doesn't work *****
pano.moveImages ;


If you want to call pano.moveImages , use '()':


thanks - that does the trick.
--
http://www.niftybits.ukfsn.org/

remove 'n-u-l-l' to email me. html mail or attachments will go in the spam
bin unless notified with [html] or [attachment] in the subject line.

May 24 '06 #6
Andy Baxter <ne***@earthson g.null.free-online.co.uk> writes:
RobG said:
Andy Baxter wrote:
var pano = {
// initialisation for the panorama.
// pixels to move when mouse is at full left / right.
scale: 0,
// mouse status.
mouseDown: 0, ..... // initialise variables;
scale=30;
mouseDown=0;
....
You must be very careful with creating variables this way. Omitting
'var' means that before pano.init() is called, they are all undefined.
After pano.init() is called, they are all global variables. Perhaps
they should be properties of pano?


I thought they were - I was assuming that once I'd declared them as
properties of pano, then after that I could refer to them as such without
the 'var'. I think I'm still thinking javascript is like C++ when it
isn't.


You are. Scoping in Javascript is not as automatic as in, e.g., C++ or
Java.

To assign a property to an object, you must refer to the object, so
you should write
this.scale = 30;
this.mouseDown = 0;
etc.

As a shorthand, that should be used carefully, you can open an object
as a scope with the "with" statement:

with(this) {
scale = 30;
mouseDown = 0;
// ..
}

It will make properties of the "this" object appear as variables in
the created scope. You should be careful about using any other
variables than the ones you know are there, since there is no way
of knowing what unknown properties an object by have in some
obscure browser or an environment where Object.prototyp e has been
"enhanced".
/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.'
May 24 '06 #7
Lasse Reichstein Nielsen wrote:
To assign a property to an object, you must refer to the object, so
you should write
this.scale = 30;
this.mouseDown = 0;
etc.

As a shorthand, that should be used carefully, you can open an object
as a scope with the "with" statement:

with(this) {
scale = 30;
mouseDown = 0;
// ..
}

It will make properties of the "this" object appear as variables in
the created scope.


No, it will not. Instead, this is not different than using no `with'
statement. Exactly because the meaning of write and read access differ
within a with-block, the `with' statement is deprecated.

// assignment to undeclared variable bar
function Foo() { with (this) { bar = 42; } }

// reference to undefined property (new Foo()).bar
(new Foo()).bar

// 42
bar
PointedEars
--
Multiple exclamation marks are a sure sign of a diseased mind.
-- Terry Pratchett
May 25 '06 #8
Thomas 'PointedEars' Lahn <Po*********@we b.de> writes:
Lasse Reichstein Nielsen wrote:
with(this) {
scale = 30;
mouseDown = 0;
// ..
}

It will make properties of the "this" object appear as variables in
the created scope.


No, it will not.


Yes, it will.

What it will not do is to make assignments to non-properties create
properties. The existing properties *will* work as variables in
the created scope, assignment and all.

var x = {foo:37};
with(x) {
foo = 42;
bar = "not";
}
alert([x.foo,bar]); // 42,"not"
Instead, this is not different than using no `with'
statement. Exactly because the meaning of write and read access differ
within a with-block, the `with' statement is deprecated.
The reason use of the with statment is not encouraged is that it
is hard to control which variables are introduces, since properties
of objects can be introduced by many different and unpredictable
sources, both the browser and other code.
// assignment to undeclared variable bar
function Foo() { with (this) { bar = 42; } }


The difference from the example given is that "bar" is not a property
of the "this" object at the point of the assignment. Had it been, that
property would have been assigned to.

/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.'
May 25 '06 #9

Matt Kruse wrote:

Using objects as a "namespace" to encapsulate functions is a good idea.
<snip>
If
you are building reusable code, however, encapsulating functionality into a
namespace is a good idea.


And there are two other current threads here that are debating the pros
and cons of this.

Matt, I'm curious what you think about the perfomance loss due to the
extra '.' resolution of a simulated namespace. The other option is
using a prefix to make things unique.

Peter

May 25 '06 #10

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

Similar topics

11
3185
by: Guotao Luan | last post by:
Hello All: I notice that there have been frequent questions being asked about template here so I guess it is okay to post this message here. I just wrote a c++ tempalte tutorial/review, I would like to hear feedbacks from other users. I do not have much experience with template myself so I am sure there are many problems or even mistakes in...
4
1685
by: binnyva | last post by:
Hello Everybody, I am writing an interactive tutorial for JavaScript. I created a text box into which the users can input javascript commands. On pressing a button, these commands will be evaluated. It works fine - but won't show any error if the commands are wrong. Is there a way to show an error if the 'eval' command encounters an...
7
1588
by: Tim Johnson | last post by:
I'm an experienced programmer, but new to Javascript. For OOP: python and C++ backgrounds, among others I have one book on js - (Javascript Application Cookbook). I'd welcome further recommendations. 1)Small "recipes" 2)Object models 3)Examples 4)Tutorials appropriate for JS Newbie but 'old' coder.
15
4190
by: binnyva | last post by:
Hello Everyone, I have just compleated a JavaScript tutorial and publishing the draft(or the beta version, as I like to call it) for review. This is not open to public yet. The Tutorial is avaliable at... http://www.geocities.com/binnyva/code/javascript/advanced_tutorial/ If any of you could spare the time, please have a look at my...
11
2243
by: Alan Silver | last post by:
Hello, I am a seasoned Classic ASP programmer who is interested in learning ASP.NET. I bought a book (Que's Special Edition Using ASP.NET) which is complete rubbish, and would like a recommendation of something better. I have a very basic idea of how ASP.NET works having spent a couple of days playing with it, but it's still a large...
9
4158
by: julie.siebel | last post by:
Hello all! As embarrassing as it is to admit this, I've been designing db driven websites using javascript and vbscript for about 6-7 years now, and I am *horrible* at form validation. To be honest I usually hire someone to do it for me, grab predone scripts and kind of hack out the parts that I need, or just do very minimal validation...
2
1289
by: Turbo | last post by:
Here is small javascript that i aggregated using various sources from web. Please comment if you find it useful. http://sandy007smarty.seo.iitm.ac.in/2006/09/26/javascript-tutorial/
2
1971
by: Bundy | last post by:
Hi On my webpages I have replaced the submit button with a rolling submit button using the script below (Script 1). This script is used by many of my webpages and is included in a external file. There are two webpages that use onSubmit event handler to fire a script in an external file but the event handler is no longer firing. onSubmit...
3
2388
by: Randy Smith | last post by:
Hi, It appears as though we will have a new coding standard for field validation that includes "IsPageValid". I've been unable to find anything about this on the "microsoft.com" site by googling "IsPageValid". Anyway, does anyone have any experience with this technique, and if so, can you recommend a tutorial or sample on it? It is much...
0
7465
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...
0
7398
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...
0
7805
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...
0
7752
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...
0
5969
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...
1
5325
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...
0
3449
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...
0
3441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1013
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.