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

invoking a method when I have it's name as a string

Hi,

I'm trying to figure out how to invoke a method on an object given the
object and the method name. For example, here's a simple object with a
method:

function MyObj (pName, pDesc) {
this.name = pName;
this.desc = pDesc;
MyObj.prototype.foo = function() {
return this.name + " - " + this.desc;
}
}

and here is some sample code to manipulate it.

var o1 = new MyObj("nn", "dd");
var s1 = o1.foo();

The assignment to s1 invokes the foo method and gets back the string "nn -
dd" as expected. now I try to find the foo method by it's name:

var funcName = "foo";
var theFunc = o1[funcName];
var s2 = theFunc();

the assignment to s2 invokes the function OK, but not in the context of the
object. can someone tell me how to invoke a function as a method?

Andy

Jul 20 '05 #1
7 9664
"Andy Fish" <aj****@blueyonder.co.uk> writes:
The assignment to s1 invokes the foo method and gets back the string "nn -
dd" as expected. now I try to find the foo method by it's name:

var funcName = "foo";
var theFunc = o1[funcName];
var s2 = theFunc();

the assignment to s2 invokes the function OK, but not in the context of the
object. can someone tell me how to invoke a function as a method?


theFunc.call(o1)

There are two methods of function objects that allow them to pretend to
be methods: "call" and "apply". The only difference is in how they transfer
the arguments to the function. "Call" takes the arguments one at a time,
and "apply" takes them as one array (and it is a type error if the second
argument of "apply" isn't an array).

function myFunc(arg1,arg2,arg3) {...}

myFunc.call(myObj,arg1,arg2,arg3);
myFunc.apply(myObj,[arg1,arg2,arg3]);

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #2
Thanks, I'd missed that one

hey, this javascript stuff ain't so bad after all... :-)

"Lasse Reichstein Nielsen" <lr*@hotpop.com> wrote in message
news:fz**********@hotpop.com...

theFunc.call(o1)

There are two methods of function objects that allow them to pretend to
be methods: "call" and "apply". The only difference is in how they transfer the arguments to the function. "Call" takes the arguments one at a time,
and "apply" takes them as one array (and it is a type error if the second
argument of "apply" isn't an array).

function myFunc(arg1,arg2,arg3) {...}

myFunc.call(myObj,arg1,arg2,arg3);
myFunc.apply(myObj,[arg1,arg2,arg3]);

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'

Jul 20 '05 #3
"Andy Fish" <aj****@blueyonder.co.uk> wrote in message
news:t6*******************@news-text.cableinet.net...
Hi,

I'm trying to figure out how to invoke a method on an object given the
object and the method name. For example, here's a simple object with a
method:

function MyObj (pName, pDesc) {
this.name = pName;
this.desc = pDesc;
MyObj.prototype.foo = function() {
return this.name + " - " + this.desc;
}
}

and here is some sample code to manipulate it.

var o1 = new MyObj("nn", "dd");
var s1 = o1.foo();

The assignment to s1 invokes the foo method and gets back the string "nn -
dd" as expected. now I try to find the foo method by it's name:

var funcName = "foo";
var theFunc = o1[funcName];
var s2 = theFunc();

the assignment to s2 invokes the function OK, but not in the context of the object. can someone tell me how to invoke a function as a method?


var funcName = "foo";
var s2 = o1[funcName]();
Jul 20 '05 #4


Andy Fish wrote:
Hi,

I'm trying to figure out how to invoke a method on an object given the
object and the method name. For example, here's a simple object with a
method:

function MyObj (pName, pDesc) {
this.name = pName;
this.desc = pDesc;
MyObj.prototype.foo = function() {
return this.name + " - " + this.desc;
}
}

and here is some sample code to manipulate it.

var o1 = new MyObj("nn", "dd");
var s1 = o1.foo();

The assignment to s1 invokes the foo method and gets back the string "nn -
dd" as expected. now I try to find the foo method by it's name:

var funcName = "foo";
var theFunc = o1[funcName];
var s2 = theFunc();

the assignment to s2 invokes the function OK, but not in the context of the
object. can someone tell me how to invoke a function as a method?


Once you assign the method to a variable that function is unbound thus
don't do that, simply call the method on the object
var s2 = o1[funcName]()

--

Martin Honnen
http://JavaScript.FAQTs.com/

Jul 20 '05 #5
Hmm, now I'm confused again. how come this works:

var s2 =(o1[funcName])();

works but this doesn't:

var theFunc = o1[funcName];
var s2 = theFunc();

you'll notice I even put o1[funcName] in brackets for the first example,
which surely must force it to be evaluated as an expression which evaluates
to a value which should be able to be stored in a variable. I even tried
this slightly strange construct:

var s2 =(theFunc = o1[funcName])();

and that doesn't work either.

"Vjekoslav Begovic" <vj*******@inet.hr> wrote in message
news:bh**********@sunce.iskon.hr...
"Andy Fish" <aj****@blueyonder.co.uk> wrote in message
news:t6*******************@news-text.cableinet.net...
Hi,

I'm trying to figure out how to invoke a method on an object given the
object and the method name. For example, here's a simple object with a
method:

function MyObj (pName, pDesc) {
this.name = pName;
this.desc = pDesc;
MyObj.prototype.foo = function() {
return this.name + " - " + this.desc;
}
}

and here is some sample code to manipulate it.

var o1 = new MyObj("nn", "dd");
var s1 = o1.foo();

The assignment to s1 invokes the foo method and gets back the string "nn - dd" as expected. now I try to find the foo method by it's name:

var funcName = "foo";
var theFunc = o1[funcName];
var s2 = theFunc();

the assignment to s2 invokes the function OK, but not in the context of

the
object. can someone tell me how to invoke a function as a method?


var funcName = "foo";
var s2 = o1[funcName]();

Jul 20 '05 #6
Lasse Reichstein Nielsen <lr*@hotpop.com> writes:
For the full explanation, you will have to read the ECMA 262
specification[1]


and the missing footnote is
[1] <URL:http://www.ecma-international.org/publications/standards/ECMA-262.HTM>

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #7
"Lasse Reichstein Nielsen" <lr*@hotpop.com> wrote in message
news:pt**********@hotpop.com...
"Andy Fish" <aj****@blueyonder.co.uk> writes:
Hmm, now I'm confused again. how come this works:

var s2 =(o1[funcName])();

works but this doesn't:

var theFunc = o1[funcName];
var s2 = theFunc();

you'll notice I even put o1[funcName] in brackets for the first example,
which surely must force it to be evaluated as an expression which evaluates to a value which should be able to be stored in a variable.


Not really. Brackets are only grouping, not meaningful

<snip>

OK, I get it now.

I thought that by putting brackets round it, I would force it to be a
"normal" expression (i.e. one with only one value). It all makes sense when
you add in the concept of reference expressions.

I prostrate myself at the master of javascript, sorry ECMAScript.

Andy

Jul 20 '05 #8

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

Similar topics

1
by: magne | last post by:
I have an http module (not made by me): To connect to a server and send a request, there is a method like this: public void sendRequest(String query){ .... } When the server responds, it...
6
by: cppaddict | last post by:
Hi, The following class containing a member and a method with the same name will not compile: class Test { private: bool x; public: Test() : x(true) {};
6
by: Rene Mansveld | last post by:
Hi, how can I create an instance (object) of a class (form) if I only know the classname (VB.NET 1.0)? I need to do this in a complex app where jobs consist of parts. Each part's data is saved...
3
by: cartoper | last post by:
I am currently doing some R&D. The objective is to learn how to invoke methods via reflection using the InvokeMember method. The InvokeMember method throws an exception: Method...
4
by: Don | last post by:
Let's say I have a type name stored in a string (e.g. Dim typeName As String = "Decimal"). Is it possible to CType() a variable to the type whose name is stored in that string? e.g. Dim...
0
by: dejawoo | last post by:
Hi, I vebeen digging couple of days internet to find some solid information. Unfortunately no luck. I have seen similar question I just want to append it here I am trying to get a reference...
3
by: Robert Dailey | last post by:
Hi, I have a string in the following format: "00:00:25.886411" I would like to pass this string into the datetime.time() class and have it parse the string and use the values. However, the...
3
by: Peeyush81 | last post by:
Hi, I have created a win32 dll with an exported method. extern "C" __declspec(dllexport) void LocateAddress(struct stLocateAddressParam arrAddressParam,int nClientType, LPTSTR outptr); In...
3
by: Ryan Liu | last post by:
Hi, When i add a connection string FpConnStr from application setting UI in VS 2008, it ends with sth. like: <connectionStrings> <clear /> <add...
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:
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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?
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...
0
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,...
0
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...

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.