473,761 Members | 8,463 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting a reference to the currently executing function object

Hi,

I need to be able to do this:

var func = new Function("var me = <selfRef>; alert(me.params );");
func.params = "This is a test parameter";
window.setTimeo ut(func, 500);

Basically, I need to add properties to a function object and access
them within the function when it is executing. Therefore, I need to be
able to replace <selfRefin the above example with an expression that
would resolve to the reference to the executing function object.
Note that another use I have for this is when setting the
onreadystatecha nge property of the XMLHttpRequest object to a function
reference.

I found one way that would work:

function whoAmI()
{
return whoAmI.caller;
}

Then, replace <selfRefabove with whoAmI(). However, this seems a bit
hacky to me and may not be the most efficient. Also, I have read that
the caller property has been deprecated and may not work in all
browsers.
I am trying to avoid using closures as they are complicated and
non-intuitive for most developers and can cause memory leaks in
browsers if not used properly
(http://www.jibbering.com/faq/faq_notes/closures.html).

Any ideas?

Dec 4 '06 #1
5 2482

re****@gmail.co m wrote:
Hi,

I need to be able to do this:

var func = new Function("var me = <selfRef>; alert(me.params );");
func.params = "This is a test parameter";
window.setTimeo ut(func, 500);

Basically, I need to add properties to a function object and access
them within the function when it is executing. Therefore, I need to be
able to replace <selfRefin the above example with an expression that
would resolve to the reference to the executing function object.
Note that another use I have for this is when setting the
onreadystatecha nge property of the XMLHttpRequest object to a function
reference.

I found one way that would work:

function whoAmI()
{
return whoAmI.caller;
}

Then, replace <selfRefabove with whoAmI(). However, this seems a bit
hacky to me and may not be the most efficient. Also, I have read that
the caller property has been deprecated and may not work in all
browsers.
I am trying to avoid using closures as they are complicated and
non-intuitive for most developers and can cause memory leaks in
browsers if not used properly
(http://www.jibbering.com/faq/faq_notes/closures.html).

Any ideas?
1. Do not use "new Function('<func tion code>')" when you know all the
details of a function before runtime. This has all the drawbacks of
using eval: it's hugely inefficient. I'm disappointed to see that the
CLJ FAQ still has a lot of code examples using "new Function" when the
function constructor

var func = function(args) { /* code */ }
or
function func(args) { /* code */ }

is preferred.

2. You're looking for arguments.calle e - this is the reference to the
currently executing function, even an anonymous one.

3. Have you looked into the "this" and "prototype" keywords for
creating extensible objects? This may be the best solution for what
you're trying to do:

function Funk() { this.params = {}; }

Funk.prototype. setParam = function(key, value) {
this.params[param] = value;
}

var f = new Funk;
f.setParam('mon keys', 23);
f.setParam('fru it', 'grapes');
for (var p in f.params) { alert(p + ':' + f.params[p]); }

Dec 4 '06 #2
David Golightly wrote:

[snip]
function Funk() { this.params = {}; }

Funk.prototype. setParam = function(key, value) {
this.params[param] = value;
}
Close...

Funk.prototype. setParam = function(key, value) {
this.params[key] = value;
}

Mick
var f = new Funk;
f.setParam('mon keys', 23);
f.setParam('fru it', 'grapes');
for (var p in f.params) { alert(p + ':' + f.params[p]); }
Dec 4 '06 #3

mick white wrote:
David Golightly wrote:

[snip]
function Funk() { this.params = {}; }

Funk.prototype. setParam = function(key, value) {
this.params[param] = value;
}

Close...

Funk.prototype. setParam = function(key, value) {
this.params[key] = value;
}

Mick
var f = new Funk;
f.setParam('mon keys', 23);
f.setParam('fru it', 'grapes');
for (var p in f.params) { alert(p + ':' + f.params[p]); }
Right, that's what I meant :) Thanks, Mick.

David

Dec 4 '06 #4
David Golightly wrote:
re****@gmail.co m wrote:
<snip>
>var func = new Function("var me = <selfRef>; alert(me.params );");
func.params = "This is a test parameter";
window.setTime out(func, 500);
<snip>
1. Do not use "new Function('<func tion code>')" when you
know all the details of a function before runtime.
This is not a reasonable statement as it disregards the possibility that
the desired outcome may be multiple unique function objects created in a
way that avoided the creation of closures.
This has all the drawbacks of using eval:
Not by any means. It may have many of the drawbacks of - eval - but
using the Function constructor does not result in the direct execution
of its string argument, and also allows some control over the
environment in which the string of code used is executed (the
potentially independent provision of formal parameters for the function
and the mixing of that string with other code that may, for example,
mask out sensitive aspects of the global environment).
it's hugely inefficient.
That very much depends on the environment. In IE6 the use of the
Function constructor can be the fastest method of creating a function
object (which is significant for people writing for an IE only context
and needing performance.
I'm disappointed to see that the
CLJ FAQ still has a lot of code examples using "new Function"
when the function constructor

var func = function(args) { /* code */ }
or
function func(args) { /* code */ }

is preferred.
<snip>

Preferred by whom, and why? The code for those FAQ entries originate at
a time when inner functions were not well supported (as they were not
formally specified until ECMA 262 3rd Edition.). That makes them old but
they have not stopped working (or being less well supported) in the
meanwhile. Previous discussions on the subject have never exposed any
technical justification for changing them, just vague personal
pretences. While switching to using inner functions means forming
closures, and so in many cases having to write additional code to
mitigate IE's memory leak problem.

Blanket injunctions without justification are very dangerous things.
They tend to leave some people doing things without understanding why
they are doing them. As with most things, what should be 'preferred' is
a good technical understanding of how javascript behaves. That allows
people to make informed design decisions about what is appropriate in
their specific context.

Richard.
Dec 9 '06 #5
VK

re****@gmail.co m wrote:
var func = new Function("var me = <selfRef>; alert(me.params );");
func.params = "This is a test parameter";
window.setTimeo ut(func, 500);

Basically, I need to add properties to a function object and access
them within the function when it is executing. Therefore, I need to be
able to replace <selfRefin the above example with an expression that
would resolve to the reference to the executing function object.
Note that another use I have for this is when setting the
onreadystatecha nge property of the XMLHttpRequest object to a function
reference.

I found one way that would work:

function whoAmI()
{
return whoAmI.caller;
}
From this point I've got a bit confused of your actual: if "executing
function object" then why "caller" ? (unless a typo instead of "callee"
?)

Basically there can be two basic tasks:

1) The function is called as a method of an object instance and you
want a reference to that instance.

2) You want a reference to the executing function within the function
itself.

////////////

1) ... (ask if it was the case)

2) arguments.calle e holds the needed reference. Within the "VK's
Augmentation" :-)) messing with strings forming the function body may
get really... messy. This way I prefer to have a conventional function
to edit and toString method overloaded to use with Function
constructor:
<script type="text/javascript">

function F(arg) {
var func = new Function(F.f);
func.params = 'Test';
window.setTimeo ut(func, 500);
}

/* Edit body as you used to */
F.f = function() {
window.alert(ar guments.callee['params']);
}
/* Function constructor pickup start */
F.f.$tS = F.f.toString;
F.f.toString = function() {
var b = F.f.$tS();
return b.substring(b.i ndexOf('{')+1, b.lastIndexOf(' }')-1);
}
/* Function constructor pickup end */

function init() {
F();
}

window.onload = init;
</script>
What I like is an ability to reference static member or clone it with
the same object:

function F(arg) {
// clone for individual use:
var func = new Function(F.f);

// shared static:
var func = F.f;
}

Dec 9 '06 #6

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

Similar topics

4
9634
by: Murat Tasan | last post by:
i have a quick question... is there a way to obtain the reference to the object which called the currently executing method? here is the scenario, i have a class and a field which i would like to populate with a reference to the object that constructed this current object. i would attempt to accomplish this by setting the appropriate field from within the constructor... i figured it might be obtainable from the stack trace, but that...
303
17743
by: mike420 | last post by:
In the context of LATEX, some Pythonista asked what the big successes of Lisp were. I think there were at least three *big* successes. a. orbitz.com web site uses Lisp for algorithms, etc. b. Yahoo store was originally written in Lisp. c. Emacs The issues with these will probably come up, so I might as well mention them myself (which will also make this a more balanced
6
22532
by: Martin | last post by:
I'd like to be able to get the name of an object instance from within a call to a method of that same object. Is this at all possible? The example below works by passing in the name of the object instance (in this case 'myDog'). Of course it would be better if I could somehow know from within write() that the name of the object instance was 'myDog' without having to pass it as a parameter. //////////////////////////////// function...
15
2972
by: sara | last post by:
Hi I'm pretty new to Access here (using Access 2000), and appreciate the help and instruction. I gave myself 2.5 hours to research online and help and try to get this one, and I am not getting it. Simple database: I want to have a user enter Supply Orders (just for tracking purposes) by Item. The user may also enter a new item - "new" is a combination of Item, PartNumber and Vendor - they could have the
4
1560
by: - R | last post by:
Hello all. I'm new to .Net so please help me out. I have a application with several "Threads" running to observe various things. From time to time each thread need to add an log entry, which is displayed on a form (a datagrid on a form) there is no database, but i created a dataset using the designer. One Entity/Table is called Log and contains the log-entries.
5
4877
by: Joseph Geretz | last post by:
Here's my first attempt at DIME (code below signature). I'ts basically straight out of Microsoft's online sample: For some reason, the statement respContext.Attachments.Add(dimeAttach); trips the following error: Object reference not set to an instance of an object.
4
4604
by: chippy | last post by:
I am finding that when I use the cloneNode method to copy an HTML element that contains a <script> tag, the contents of the <script> tag, (ie. the javascript) are removed. If I do this: var form1 = document.getElementById(sID).firstChild.cloneNode(true); alert(form1.outerHTML); I can see the empty <script> tags. I am wondering if there is a reasonable workaround for this, because I need the script tag with its
7
3984
by: George2 | last post by:
Hello everyone, I am reading some code from other people, there are some code like this, class Foo { };
275
12365
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
0
9336
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
9765
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
8770
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...
0
6603
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
5215
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...
0
5364
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3866
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
3
3446
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2738
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.