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

Passing an object while dynamically calling a function

Hi All,

I need to call a function(loaded with appendChild) for which I have the
name as a string.

....
var fnName = 'fn1';
var call = fnName + '('+ param +' )';
eval(call);

It works fine as long as the param is a string but when I try to pass
an object it does not work as toString kicks in. Is there a better way
of doing this other than eval? How can I pass an object to fn1? I
thought about marshalling but I hope there's a better way inside the
language. Can someone help me understand this?

Regards,
Sebastian

Jun 27 '06 #1
5 4977
To clarify this - I do not expect eval to work on anything but string.
That said, my hope is that Javascript has a way of getting a reference
to a function "by name" so I can avoid the need of marshalling and
using eval.

sf****@gmail.com wrote:
Hi All,

I need to call a function(loaded with appendChild) for which I have the
name as a string.

...
var fnName = 'fn1';
var call = fnName + '('+ param +' )';
eval(call);

It works fine as long as the param is a string but when I try to pass
an object it does not work as toString kicks in. Is there a better way
of doing this other than eval? How can I pass an object to fn1? I
thought about marshalling but I hope there's a better way inside the
language. Can someone help me understand this?

Regards,
Sebastian


Jun 27 '06 #2
sf****@gmail.com wrote:
To clarify this - I do not expect eval to work on anything but string.
That said, my hope is that Javascript has a way of getting a reference
to a function "by name" so I can avoid the need of marshalling and
using eval.
Please don' t top-post, now everyone has to scroll down to the bottom
to see what you are talking about, then come back to the top to see the
reply.

All functions declared in a global scope are properties of the global
object. JavaScript provides two methods for getting references to
object properties - dot notation and square bracket notation.

To reference a global function using square bracket notation:

function foo() {...}

window['foo']();
To use a varaible:

var bar = 'foo';
window[bar](); // calls foo();
You use dot notation where the string supplied is the name of the
property you want to access (e.g. window.foo() in the above) and use
use square bracket notation when you want the supplied parameter to be
evaluated - 'foo' evaluates to foo, as does bar.

One final note, the window object may not be available in every user
agent that runs your script, so you might want to use the global object
instead (they are synonymous in browsers):

// Declare in global scope:
var _global = this;
Now use _global wherever you would have used window.

sf****@gmail.com wrote:
Hi All,

I need to call a function(loaded with appendChild) for which I have the
name as a string.
How do you load a function using appendChild? Or do you load the
script element containing the function using appendChild?

var fnName = 'fn1';
var call = fnName + '('+ param +' )';
call is a method of the Function object, so not really a good name for
a variable (personal preference). To do what you want here (without
eval):

var _global = this;
var fnName = 'fn1';
var call = _global[fnName];

call is now a reference to the (presumably) function object fn1, and
call() should execute it.
eval(call);

It works fine as long as the param is a string but when I try to pass
an object it does not work as toString kicks in. Is there a better way
of doing this other than eval? How can I pass an object to fn1? I
You never 'pass an object' - you always 'pass' a reference to an
object.

A fundamental principle of JavaScript is that where a variable is
assigned a primitive value, then:

var a = 5;
var b = a;

Both a and b now have a value of 5, it is effectively copied to b.
Modifying the value of a will not have any effect on the value of b.

When a variable is assigned a value that is a reference to an object,
then:

var objA = new Object();
var objB = objA;

The value of objA is a *reference* to the object, so the reference is
copied to the value of objB. objA and objB now reference the same
object. Therefore modifying (the object referenced by) objA will also
modify (the object referenced by) objB - it is the same object.

So wherever the value of a variable is assigned to some other variable
( var b = a) its value is always copied, just that sometimes it is a
primitive value and other times it is a reference to an object. You
may hear the saying 'primitives are passed by value, objects are passed
by reference' - don't believe it, for me it completely obfuscated what
is really happening.

thought about marshalling but I hope there's a better way inside the
language. Can someone help me understand this?


I hope I did! :-)

If not, please let me know.

--
Rob

Jun 28 '06 #3
RobG wrote:
sf****@gmail.com wrote:
To clarify this - I do not expect eval to work on anything but string.
That said, my hope is that Javascript has a way of getting a reference
to a function "by name" so I can avoid the need of marshalling and
using eval.
Please don' t top-post, now everyone has to scroll down to the bottom
to see what you are talking about, then come back to the top to see the
reply.


My apologies... one more thing to know :)
Not to blame it on Google Groups but probably they should discourage
this by not placing the cursor at the top of the textarea on replies ..

All functions declared in a global scope are properties of the global
object. JavaScript provides two methods for getting references to
object properties - dot notation and square bracket notation.

To reference a global function using square bracket notation:

function foo() {...}

window['foo']();
To use a varaible:

var bar = 'foo';
window[bar](); // calls foo();
You use dot notation where the string supplied is the name of the
property you want to access (e.g. window.foo() in the above) and use
use square bracket notation when you want the supplied parameter to be
evaluated - 'foo' evaluates to foo, as does bar.

One final note, the window object may not be available in every user
agent that runs your script, so you might want to use the global object
instead (they are synonymous in browsers):

// Declare in global scope:
var _global = this;
Now use _global wherever you would have used window.

sf****@gmail.com wrote:
Hi All,

I need to call a function(loaded with appendChild) for which I have the
name as a string.
How do you load a function using appendChild? Or do you load the
script element containing the function using appendChild?
Right, it's the script that contains the function that gets loaded.

var fnName = 'fn1';
var call = fnName + '('+ param +' )';
call is a method of the Function object, so not really a good name for
a variable (personal preference). To do what you want here (without
eval):

var _global = this;
var fnName = 'fn1';
var call = _global[fnName];

call is now a reference to the (presumably) function object fn1, and
call() should execute it.
Excellent! Thanks Rob.
eval(call);

It works fine as long as the param is a string but when I try to pass
an object it does not work as toString kicks in. Is there a better way
of doing this other than eval? How can I pass an object to fn1? I
You never 'pass an object' - you always 'pass' a reference to an
object.

A fundamental principle of JavaScript is that where a variable is
assigned a primitive value, then:

var a = 5;
var b = a;

Both a and b now have a value of 5, it is effectively copied to b.
Modifying the value of a will not have any effect on the value of b.

When a variable is assigned a value that is a reference to an object,
then:

var objA = new Object();
var objB = objA;

The value of objA is a *reference* to the object, so the reference is
copied to the value of objB. objA and objB now reference the same
object. Therefore modifying (the object referenced by) objA will also
modify (the object referenced by) objB - it is the same object.

So wherever the value of a variable is assigned to some other variable
( var b = a) its value is always copied, just that sometimes it is a
primitive value and other times it is a reference to an object. You
may hear the saying 'primitives are passed by value, objects are passed
by reference' - don't believe it, for me it completely obfuscated what
is really happening.
My understanding is that it's pretty similar to Java where everything
gets passed "by value", which in the case of non-primitive values is
actually "the value of the reference".

It means you can change the value of the reference but not the
reference itself (similar to the C++ pass by pointer).

It's quite tricky when it comes to passing Javascript functions along,
I don't get that yet either..

thought about marshalling but I hope there's a better way inside the
language. Can someone help me understand this?


I hope I did! :-)

If not, please let me know.

--
Rob


You sure did :)

Thank you,
Sebastian

Jun 28 '06 #4
sf****@gmail.com writes:
Hi All,

I need to call a function(loaded with appendChild) for which I have the
name as a string.

...
var fnName = 'fn1';
var call = fnName + '('+ param +' )';
eval(call);

It works fine as long as the param is a string but when I try to pass
an object it does not work as toString kicks in.
I'm surprised that the string works. It should only work for values
that has string representations that are also literal expressions
of the value (number, boolean, null, undefined and probably also
functions).
Is there a better way of doing this other than eval?
If you have the name of the function, and that is the name
it is available as in the global scope, you can either do
global scope lookup or use eval. In either case, only do
it on the function name and do the call directly. No need
to create a string containing the call and the evaluate it.

I.e., either (e.g.):

function globalVar(name) {
return this[name];
}
globalVar(fnName)(param);

or

eval(fnName)(param);
How can I pass an object to fn1?


The same way you would always do it: call the function. Going through
a string representation of a call is a detour, not a shortcut :)

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jun 28 '06 #5
JRS: In article <11*********************@75g2000cwc.googlegroups.c om>,
dated Wed, 28 Jun 2006 08:03:18 remote, seen in
news:comp.lang.javascript, sf****@gmail.com posted :
My apologies... one more thing to know :)
Not to blame it on Google Groups but probably they should discourage
this by not placing the cursor at the top of the textarea on replies ..


The cursor should be put at the top, because it facilitates removing
those parts that need not be quoted; putting it at the bottom would
encourage untrimmed quoting.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk DOS 3.3, 6.20; Win98. ©
Web <URL:http://www.merlyn.demon.co.uk/> - FAQqish topics, acronyms & links.
PAS EXE TXT ZIP via <URL:http://www.merlyn.demon.co.uk/programs/00index.htm>
My DOS <URL:http://www.merlyn.demon.co.uk/batfiles.htm> - also batprogs.htm.
Jun 29 '06 #6

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

Similar topics

5
by: kazack | last post by:
I am a little confused with code I am looking at. My c++ book does not go into passing a structure to a function so I pulled out a c book which does. and I do not understand the prototype verses...
1
by: Foxy Kav | last post by:
Hi everyone, im a first year UNI student doing a programming subject and im stuck on how to get rid of my global variables, char stringarray and char emptystring. I was wondering if anyone could...
6
by: Mark Anderson | last post by:
I have code to develop result page links (like a search engine) for some results being passed from a database where I've no server-sdide acces - thus JS. The code is below and works fine except...
0
by: Jeffrey B. Holtz | last post by:
Has anyone used the multimedia timere timeSetEvent in C#? I'm trying to use it to get a 1ms accurate timer. All the other implementations are far to inaccurate in their resolution. 1ms Timer =...
0
by: Paul Allan | last post by:
I am new to ASP.net (intermediate ASP developer). I am developing a ASP.net web application and I am having some difficulty calling and passing parameters to a function that is declared in my...
1
by: Reza Nabi | last post by:
Bakground: I have a webform (LoadCtl.aspx) which loads the user control to a placeholder dynamically based on the ctlName querystring passed in the URL. Webform (LoadCtl.aspx) also passes a...
6
by: James P. | last post by:
I'm trying to pass a sqlDataReader from a called function to a calling function but got nothing back and a message saying "An unhandled exception of type 'System.NullReferenceException' occurred in...
6
by: Simon Verona | last post by:
I would normally use code such as : Dim Customer as new Customer Dim t as new threading.thread(AddressOf Customer.DisplayCustomer) Customer.CustomerId=MyCustomerId t.start Which would create...
10
by: Sebastian Santacroce | last post by:
Hi, If I want to pass a form (forms I have created) to a function what would I set the declaration as for example Dim p as existingForm OpenForm (p, existingForm)
2
by: Joerg Battermann | last post by:
Hello there, I have a quick question: When calling a function B from within a function A, is it possible get information about the calling function A (e.g. name, values passed over etc) from...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
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
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...

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.