473,898 Members | 3,235 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

javascript passing by reference problem

ged
Hi,

i am a oo (c#) programmer, and have not used javascript for a while and
i cant work out how javascript manages its references. Object
References work for simple stuff, but once i have an object collection
and stanrd using it it starts to fall apart.
Clearly there is something about javascript's usage of passing "By ref"
that i am not getting. i have had a look on the web and found some
examples, but i cant see why my code does not work. Grrrrh. I really
need to know why because i am writng a large app in javascript and
Ajax.

I program in c# mainly and i am applying soem OO principles to my
javascript but i am goign nust with how its works sometimes.

Also on a side not i dont get why i code javaScript this way to make it
work?

var personEntity = new PersonEntity("g ed", 35);
document.write( personEntity.Na me;

function PersonEntity(na me, age)
{
var Name = name;
var Age - age;
}

it has to be instead:
function PersonEntity(na me, age)
{
this.Name = name;
this.Age = age;
}
i have a sneaking suspicion that the above example also has something
to do with my misunderstandin g of the javascript reference pointers
work.

Code is below as a complete test. You just have to save it and load
into your browser and it will run telling you where it errored. I
really want an answer on this and am trying to make it easy for someone
to tell me why is DOES NOT WOKR .

thansk in advance

Ged
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Referenc e Test</title>
<script language="JavaS cript">

// Constants maps to static UI element ids
var APP_ICON_XPLORE R_ID = "XplorerAppIcon ";
var APP_ICON_GIMP_I D = "GimpAppIco n";
var APP_PANEL_XPLOR ER_ID = "XplorerAppPane l";
var APP_PANEL_GIMP_ ID = "GimpAppPan el";

var g_appController = new AppController() ;
var g_appModel = new AppModel();

function AppInit()
{
// create app objects to map Dom Elements to other aspects
var xplorerApp = new AppItem('Xplore r', APP_ICON_XPLORE R_ID,
APP_PANEL_XPLOR ER_ID);
g_appModel.Add( xplorerApp);

var gimpApp = new AppItem('Gimp', APP_ICON_GIMP_I D,
APP_PANEL_GIMP_ ID)
g_appModel.Add( gimpApp);
// DO test of item being clicked
g_appController .AppItemLoadCom mand(APP_ICON_X PLORER_ID);

}
function AppController()
{
// App Icon clicked
this.AppItemLoa dCommand = function(id)
{

// resolve item clicked
var appItem = g_appModel.GetA ppItemByIconEle mentId(id);

document.write( "appItem.appIco nElementId : " +
appItem.appIcon ElementId + "<BR />");

// Set Model
g_appModel.SetC urrentItem(appI tem);

// Set View
var appView = AppView();
appView.SetFocu s(g_appModel.ap pList, appItem);
}
}// JScript File
function AppModel()
{
this.currentIte m = null;
this.appList = new Array();

this.Add = function(appIte m)
{
this.appList[this.appList.le ngth] = appItem;
};

this.GetAppItem ByIconElementId = function(id)
{
for(var x=0; x < this.appList.le ngth; x++)
{
if(this.appList[x].appIconElement Id == id)
{
return this.appList[x];
}
return null;
}
}

this.GetAppItem ByPanelElementI d = function(id)
{
for(var x=0; x < this.appList.le ngth; x++)
{
if(this.appList[x].appPanelElemen tId == id)
{
return this.appList[x];
}
return null;
}
}

this.SetCurrent Item = function(appite m)
{
document.write( "Testing object passed by reference now <BR
/>");
// !! This fails to have the object passed in - whats gives
?//
// Gtes appItem is Not defines in javascript console //
document.write( "appItem.appIco nElementId : " +
appItem.appIcon ElementId);
appItem.isCurre nt = true;
}

this.GetCurrent Item = function()
{
for(var x=0; x < this.appList.le ngth; x++)
{
if(this.appList[x].isCurrent == true)
{
return this.appList[x];
}
return null;
}
}
}

function AppItem(name, appIconElementI d, appPanelElement Id)
{
this.name = name;
this.appIconEle mentId = appIconElementI d;
this.appPanelEl ementId = appPanelElement Id;
this.isCurrent = false;
}

</script>

</head>
<body onLoad="javaScr ipt:AppInit();>

Reference Test

<body>

Dec 18 '05 #1
6 5587
ged wrote:
var personEntity = new PersonEntity("g ed", 35);
document.write( personEntity.Na me; ----------------------------------^
SyntaxError: missing ) after argument list
function PersonEntity(na me, age)
{
var Name = name;
var Age - age; ------------------^
SyntaxError: missing ; before statement
}

it has to be instead:
function PersonEntity(na me, age)
{
this.Name = name;
this.Age = age;
}
Of course.
i have a sneaking suspicion that the above example also has something
to do with my misunderstandin g of the javascript reference pointers
work.
Maybe. Ignoring what could be typos: local variables of a constructor
do not become properties of objects created through it.
Code is below as a complete test. You just have to save it and load
into your browser and it will run telling you where it errored. I
really want an answer on this and am trying to make it easy for someone
to tell me why is DOES NOT WOKR .
[...]
"Does not work" is a useless error description. [psf 4.11]

<URL:http://jibbering.com/faq/#FAQ4_43>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
<html xmlns="http://www.w3.org/1999/xhtml">
Neither does IE support XHTML, nor is your markup Valid XHTML 1.0
Transitional. <URL:http://validator.w3.or g/>
[...]
No, thanks.
<body onLoad="javaScr ipt:AppInit();>


Labels like `javascript:' do not belong into code in event handler attribute
values. The default scripting language should be declared via `meta'
element within the `head' element for UAs that support it according to the
HTML 4.01 Specification.

Identifiers not referring to functions used as constructors should not start
with an uppercase letter in order to avoid confusion and undesired side
effects.
PointedEars
Dec 18 '05 #2
ged wrote:
i am a oo (c#) programmer,
Your shift key seems to be intermittent. If you are going to attempt to
engage in written communication (or computer programming for that
matter) it may prove advantageous to have your keyboard serviced or
replaced.
and have not used javascript for a while and i cant work
out how javascript manages its references.
Javascript leaves the mechanism of references to objects up to the
implementers. The only important detail is that when an object property
is assigned the value 'of an object' the resulting value refers to that
object, and when a value that is 'of an object' is passed as an argument
to a function call it is the value that refers to the object that is
passed (the functions formal parameter will refer to the same object
instance).
Object References work for simple stuff, but once i have an
object collection and stanrd using it it starts to fall apart.
Implementations are consistent in the way that they handle object
references (that is, the resulting behaviour is consistent) so that is
likely to follow from some misconception.
Clearly there is something about javascript's usage of
passing "By ref" that i am not getting.
And an explanation if what it is that you are expecting is probably the
best way of getting an explanation of where your expectations do not
corresponds with reality.
i have had a look on the web and found some examples, but
i cant see why my code does not work.
But your code does work, in the sense that it does exactly what you have
programmed it to do. So the question becomes; what is it that you want
it to do? or; what would qualify as working?
Grrrrh. I really need to know why because i am writng a large
app in javascript and Ajax.
AJAX implies javascript.
I program in c# mainly and i am applying soem OO principles
to my javascript but i am goign nust with how its works
sometimes.

Also on a side not i dont get why i code javaScript this way
to make it work?

var personEntity = new PersonEntity("g ed", 35);
document.write( personEntity.Na me;

function PersonEntity(na me, age)
{
var Name = name;
var Age - age;
}
Assuming that the subtraction operation is a typo (or another symptom of
your defective keyboard), this is a futile function as a function's
formal parameters, local variables and inner function declarations
result in the creation of named properties of the 'Activation/Variable'
object that sites at the top of the scope chain form the execution of
the function body. The Activation/Variable object is only accessible
through the scope chain. (See ECMA 262, 3rd edition; Sections 10.1.4 and
10.2)

Any object created with this constructor4 will not have a public 'Name'
property, so the document.write above would output 'undefined'.
it has to be instead:
function PersonEntity(na me, age)
{
this.Name = name;
this.Age = age;
}
The - this - keyword refers to the object being constructed when this
function is used as a constructor. You create a 'Name' property of that
object and assign a value to it, so the document.write will wrote out
the value of that property.
i have a sneaking suspicion that the above example also has
something to do with my misunderstandin g of the javascript
reference pointers work.
Looks like you need to understand javascript's scopeing, identifier
resolution and the looking up/creation of properties on objects. Try:-

<URL: http://www.jibbering.com/faq/faq_notes/closures.html >

Code is below as a complete test. You just have to save it
and load into your browser and it will run telling you where
it errored. I really want an answer on this and am trying to
make it easy for someone to tell me why is DOES NOT WOKR .
Would it have been so much effort to actually write down what the error
was and indicate which line produced it. The error reported by IE is
"'appItem' is undefined" (line 96, char 9). That line is inside of the -
SetCurrentItem - method of the - AppModel - object. And it happens
because there is no object on the scope chain of that method with a
property named 'appItem'.
thansk in advance

Ged
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
<html xmlns="http://www.w3.org/1999/xhtml">
Yikes, an XHTML doctype. You don't want to be scripting XHTML in a
commercial context as the additional effort required to accommodate IE's
lack of support for XHTML considerably exceeds the negligible returns in
using that type of mark-up.
<head>
<title>Referenc e Test</title>
<script language="JavaS cript">
In valid (x)HTML the LANGUAGE attribute of SCRIPT elements is deprecated
and the TYPE attribute is required.

<script type="text/javascript">

<snip> function AppController()
{
// App Icon clicked
this.AppItemLoa dCommand = function(id)
{

// resolve item clicked
var appItem = g_appModel.GetA ppItemByIconEle mentId(id);

document.write( "appItem.appIco nElementId : " +

This is a significant problem is you int4end attempting to use XHTML as
no current XHTML DOM implementation supports the document.write method.
That is, if there is any chance of this document ever being interpreted
as anything other than error-filled HTML the code will instantly break
as the document.write calls will fail.
appItem.appIcon ElementId + "<BR />");
And if this document is intended to be served as 'text/html' and so
interpreted as error-filled HTML, error corrected back to tag-soup HTML,
and an HTML DOM created from the result (so that the document.write
method will work at all) there is little point in document.writie-ing
XHTML style mark-up. Doing so is just irrational.
// Set Model
g_appModel.SetC urrentItem(appI tem);

// Set View
var appView = AppView();
appView.SetFocu s(g_appModel.ap pList, appItem);
}
}// JScript File
It is a universally good idea to indent source code (and do so
appropriately when posting code to newsgroups, i.e. with spaces instead
of tabs). Here you have the call to the SetCurrentItem - method that
results in the error. The local variable 'appItem' has its value passed
as the argument to the method call.
function AppModel()
{
this.currentIte m = null;
this.appList = new Array();

this.Add = function(appIte m)
{
this.appList[this.appList.le ngth] = appItem;
};
This inner function expression will result in the creation of a new
function object and the assignment of a reference to that new function
object to th4e 'Add' property of this object instance. The same process
is repeated for each instantiation of an instance of 'AppModel'. The
function created is not exploiting its status as an inner function and
so there is no need for each instance of 'AppModel' to have a distinct
function object instance as its 'Add' method.
this.GetAppItem ByIconElementId = function(id)
{
for(var x=0; x < this.appList.le ngth; x++)
{
if(this.appList[x].appIconElement Id == id)
{
return this.appList[x];
}
return null;
}
}
The same as above applies to this 'GetAppItemByIc onElementId' method.
this.GetAppItem ByPanelElementI d = function(id)
{
for(var x=0; x < this.appList.le ngth; x++)
{
if(this.appList[x].appPanelElemen tId == id)
{
return this.appList[x];
}
return null;
}
}
The same as above applies to this 'GetAppItemByPa nelElementId' method.
this.SetCurrent Item = function(appite m)
Observe that you defective keyboard has bitten you here. If this
method's formal parameter had an uppercase I instead of lower case then
the error "'appItem' is undefined' would not happen as 'appItem' would
then refer to the formal parameter.
{
document.write( "Testing object passed by reference now <BR
/>");
// !! This fails to have the object passed in - whats gives
?//
// Gtes appItem is Not defines in javascript console //
document.write( "appItem.appIco nElementId : " +
appItem.appIcon ElementId); ^^^^^^^
There is your error. It looks like you intended to refer to the method's
parameter but have actually used an Identifier that does not resolve as
a named property of any object on the method's scope chain.
appItem.isCurre nt = true;
}
The same as above applies to this 'SetCurrentItem ' method.
this.GetCurrent Item = function()
{
for(var x=0; x < this.appList.le ngth; x++)
{
if(this.appList[x].isCurrent == true)
{
return this.appList[x];
}
return null;
}
}
The same as above applies to this 'GetCurrentItem ' method.
}

<snip>

All of this worthless creation of function object instances with each
creation of an ' AppModel' instance can be avoided by assigning a single
function object instance to named properties of the constructor's
prototype. E.G:-

function AppModel()
{
this.currentIte m = null;
this.appList = new Array();
}

AppModel.protot ype.Add = function(appIte m)
{
...
};
AppModel.protot ype.GetAppItemB yIconElementId = function(id)
{
...
};
AppModel.protot ype.GetAppItemB yPanelElementId = function(id)
{
...
};
AppModel.protot ype.SetCurrentI tem = function(appite m)
{
...
};
AppModel.protot ype.GetCurrentI tem = function()
{
...
};

Richard.
Dec 18 '05 #3
ged
hi Pointed Ears,

The question was about handlng variable declarations by reference (i.e.
pointers), but thanks for your pointers( excuse the pun ) about teh
docuemtn not validating agaisnt rhe w3c schema.

anyway it all was a stupid miss-typing on my part of the arguement of
the method signature - Dumb really.
Turns out JavaScript handles ponters very nicely, unlike a lot of
confused assumptions and answers i have on the net.

For anyones reading this - the answer to my question is:
The pointers are handled in the same way most OO languages manage them.
The trick is the correct use of the "this" keyword. Nested functions
are essentially methods and parent functions are classes.
As long as i rememebr this then the use of the "this" keywork is
exactly the same as in c#.

Thansk again and i consider this closed.

Regards

Gerard

Dec 18 '05 #4
ged wrote:
hi Pointed Ears,
My nickname is spelled "PointedEar s", thanks in advance.
The question was about handlng variable declarations by reference (i.e.
pointers), but thanks for your pointers( excuse the pun ) about teh
docuemtn not validating agaisnt rhe w3c schema.
(Your keyboard really /is/ dysfunctional.)

"w3c schema"? You have no clue what you are talking about.
[...]
Turns out JavaScript handles ponters very nicely, unlike a lot of
confused assumptions and answers i have on the net.

For anyones reading this - the answer to my question is:
The pointers are handled in the same way most OO languages manage them.
The trick is the correct use of the "this" keyword. Nested functions
are essentially methods and parent functions are classes.
You could not be more wrong.

1. There are no pointers in JavaScript, and object references are not
compareable to C(++/#) pointers.

2. JavaScript as implemented from NN4 to current Mozilla/5.0-based browsers,
and JScript as implemented in IE is a programming language supporting
prototype-based inheritance; there are no classes.

3. Maybe you are referring to JScript.NET for ASP.NET/IIS which also
supports class-based inheritance, however that is not JavaScript.
As long as i rememebr this then the use of the "this" keywork is
exactly the same as in c#.


No, it is not.

<URL:http://msdn.microsoft. com/library/en-us/csref/html/vclrfThisPG.asp >
<URL:http://msdn.microsoft. com/library/en-us/jscript7/html/jsstmthis.asp>
<URL:http://http://developer.mozil la.org/en/docs/Core_JavaScript _1.5_Guide:Crea ting_New_Object s:Using_this_fo r_Object_Refere nces>
<URL:http://developer.mozil la.org/js/specs/ecma-262#a-10.1.7>
PointedEars
Dec 18 '05 #5
Thomas 'PointedEars' Lahn wrote:
[...]
2. JavaScript as implemented from NN4 to current Mozilla/5.0-based
browsers,
That should have been NN2 instead, of course.
and JScript as implemented in IE is a programming language supporting
prototype-based inheritance; there are no classes.

PointedEars
Dec 18 '05 #6
In article <15************ ****@PointedEar s.de>, Thomas 'PointedEars'
Lahn <Po*********@we b.de> writes

Ears recommends that ...
Identifiers not referring to functions used as constructors should not start
with an uppercase letter in order to avoid confusion and undesired side
effects.

....but, of course, if you have an alternative scheme for avoiding
confusion then feel free to use it.

John
--
John Harris
Dec 19 '05 #7

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

Similar topics

5
10318
by: aelred | last post by:
I have a web page where a member can open up a chat window (child window) with another member. - From there the member can also navigate to other web pages. - From other pages in the site, they may also open up new chat windows with other members (just not the same one). - Each chat page is opened with the member name as the window name. - When I log off from the web page, I would like all the chat windows to automatically close. I...
0
9840
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
11259
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
10483
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
9661
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
8035
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
7187
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
5880
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
4706
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
4295
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.