473,659 Members | 3,592 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting the 'this' scope of the caller

I'm trying to write an 'each' function for a JavaScript array that
behaves like Ruby's Array#each. (It doesn't matter if you know Ruby to
help with this question.)

My problem is the scope of 'this' inside the iterator callback. I would
like it to be the same as the object that called the each() on the
array. Right now I have to do that with a closure or an
explicitly-passed 'this' scope. For example:

function Person( inName, inCats ) {
this.name = inName;
this.cats = inCats;
}

// Using a closure
Person.prototyp e.showInfo = function( ) {
var me = this;
this.cats.each( function( catName ){
alert( me.name + " owns " + catName );
} );
}

Array.prototype .each = function( inCallback ){
for ( var i=0,len=this.le ngth; i<len; ++i ){
inCallback( this[ i ], i );
}
}

phrogz = new Person( 'Gavin', [ 'Fuzzles', 'Kitty' ] );
phrogz.showInfo ( );
--Gavin owns Fuzzles
--Gavin owns Kitty
// Using an explicit scope
Person.prototyp e.showInfo = function( ) {
this.cats.each( this, function( catName ){
alert( this.name + " owns " + catName );
} );
}

Array.prototype .each = function( inScope, inCallback ){
for ( var i=0,len=this.le ngth; i<len; ++i ){
inCallback.call ( inScope, this[ i ], i );
}
}
Inside the each() function, arguments.calle e.caller would give me a
reference to the showInfo function object. What I am looking for is a
way to access the scope of the 'this' receiver within that particular
invocation of showInfo(), so that I can use it in place of inScope
without having to pass 'this' each call.
Thanks in advance for any help!

Oct 11 '06 #1
9 4014
I forgot to add (in case it matters): this is being executed by (a
slightly modified version of) the SpiderMonkey runtime. And no, I don't
have ability to change the runtime to add this capability. :)

Oct 11 '06 #2
VK

Phrogz wrote:
I'm trying to write an 'each' function for a JavaScript array that
behaves like Ruby's Array#each. (It doesn't matter if you know Ruby to
help with this question.)
Actually it does help a lot: because it is difficult to help to write a
method w/o knowing its objectives. I've missed the rails of Ruby :-)
but latest Gecko (including Firefox 1.5 or higher) has forEach method
added for Array. Please take a look at:
<http://developer.mozil la.org/en/docs/Core_JavaScript _1.5_Reference: Objects:Array:f orEach>
Is it what you want for all other UA's? If not then what is
missing/superfluous?

Oct 11 '06 #3
VK wrote:
Phrogz wrote:
I'm trying to write an 'each' function for a JavaScript array that
behaves like Ruby's Array#each. (It doesn't matter if you know Ruby to
help with this question.)

Actually it does help a lot: because it is difficult to help to write a
method w/o knowing its objectives. I've missed the rails of Ruby :-)
but latest Gecko (including Firefox 1.5 or higher) has forEach method
added for Array. Please take a look at:
<http://developer.mozil la.org/en/docs/Core_JavaScript _1.5_Reference: Objects:Array:f orEach>
Is it what you want for all other UA's? If not then what is
missing/superfluous?
What is listed there is what I have implemented (except that the order
of the callback/scope parameters are reversed).

What I would like is a forEach type method where the 'this' scope used
inside the callback is the same as the 'this' scope that was used to
invoke the forEach. For example:

G = {}
G.a = this;
myArray.each( function(){ G.b = this } );

I would like G.a===G.b

Oct 11 '06 #4
Phrogz wrote:
G = {}
G.a = this;
myArray.each( function(){ G.b = this } );

I would like G.a===G.b
I am still confusing (the above example seems to make it more
confusing).

Let met put it this way:

someone = new Person("abc", ['d','e'])
someone.cats.fo rEach( function() { alert(X)} )

You want X to be "someone", right?

That is, cats' this, but not forEach's this. Is that what you want ?

Oct 12 '06 #5
I am in turn confused by your example. :/

Let me try one more time:

function Person( inName, inCats ) {
this.name = inName;
this.cats = inCats;
}

Person.prototyp e.showCats = function( ) {
this.cats.each( function( catName ) {
alert( this.name + ' owns ' + catName );
} );
}

phrogz = new Person( 'Gavin', [ 'Fuzzles', 'Kitty' ] );
phrogz.showCats ( );

I am hoping to find a way to write the Array.prototype .each() function
so that the above code outputs:
--Gavin owns Fuzzles
--Gavin owns Kitty

Oct 12 '06 #6
Phrogz wrote:

[snip]
function Person( inName, inCats ) {
this.name = inName;
this.cats = inCats;
}

Person.prototyp e.showCats = function( ) {
this.cats.each( function( catName ) {
alert( this.name + ' owns ' + catName );
} );
}

phrogz = new Person( 'Gavin', [ 'Fuzzles', 'Kitty' ] );
phrogz.showCats ( );

I am hoping to find a way to write the Array.prototype .each() function
so that the above code outputs:
--Gavin owns Fuzzles
--Gavin owns Kitty
That isn't going to happen without modifying the showCats method, and
you've already posted the two most likely approaches.

If the each function is to be a method of the Array prototype object, it
is expected that the this operator will refer to an array (or at least
an object with a length property and numeric properties [0,length-1]).
The only other objects it can know about must either be in its scope
chain, or its argument list. The scope chain is fixed when the method is
created so that isn't an option, and if the argument list is
unacceptable then responsibility must fall to the callback to retain any
necessary information.

Mike
Oct 12 '06 #7
Michael Winter wrote:
Phrogz wrote:
I am hoping to find a way to write the Array.prototype .each() function
so that the above code outputs:
--Gavin owns Fuzzles
--Gavin owns Kitty

That isn't going to happen without modifying the showCats method, and
you've already posted the two most likely approaches.
Thanks for the confirmation. I was hoping that there might be some
feature (in ECMAScript or SpiderMonkey specifically) that allowed you
to access the receiver that invoked a method as part of the call stack
browsing.

It's not altogether surprising that it doesn't exist, but would
certainly be nice in a situation like this. Oh well.

(It looks[1] like SpiderMonkey might have had this at one time as a
"__caller__ " property, but it was yanked. It's not in my (older)
SpiderMonkey release, unfortunately.)

[1]
http://developer.mozilla.org/en/docs...unction:caller

Oct 12 '06 #8
Phrogz wrote:

[snip]
I was hoping that there might be some feature (in ECMAScript or
SpiderMonkey specifically) that allowed you to access the receiver
that invoked a method as part of the call stack browsing. It's not
altogether surprising that it doesn't exist, but would certainly be
nice in a situation like this. Oh well.
It's not entirely unusual, either: the issue also arises when attempting
to assign a method of some object as an event listener. When the
listener is invoked, the this operator will refer to the element to
which the listener is attached, not the object from which the listener
originated. The general solution is much the same: use a closure and
store a reference to the object in the scope chain of that function.

[snip]

Mike
Oct 12 '06 #9
VK

Phrogz wrote:
What I would like is a forEach type method where the 'this' scope used
inside the callback is the same as the 'this' scope that was used to
invoke the forEach. For example:

G = {}
G.a = this;
myArray.each( function(){ G.b = this } );

I would like G.a===G.b
I'm not using prototype for such tricky things, and sure you are not
doing it to alert cats' names :-) so depending on the real purpose it
can be not suitable. But withing the spelled requirements I would do it
this way (keeping all methods as static):
<html>
<head>
<title>Cats</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script type="text/javascript">

function Person(inName, inCats) {
this.name = inName;
this.cats = inCats;
this.cats.each = each;
this.cats.conte xt = this;
this.showCats = Person.showCats ;
}

Person.showCats = function() {
this.cats.each( alertCat);
}

function each(fnCallBack ) {
for (var i=0; i<this.length; i++) {
fnCallBack.call (this.context, this[i]);
}
}

function alertCat(catNam e) {
window.alert(th is.name + ' has ' + catName);
}

phrogz = new Person('Gavin', ['Fuzzles', 'Kitty']);
phrogz.showCats ();

</script>
</head>

<body>

</body>
</html>

Oct 12 '06 #10

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

Similar topics

1
2182
by: Martin Ziebart | last post by:
Hi ! The following PHP-Code: >> $conn=pg_connect ($conn_string); >> $query=pg_exec ($conn, $sql_statement); // it's pg_query for PHP >4.2.0 >> pg_close ($conn);
2
1959
by: Indrid Cold | last post by:
Is there a way to call a function so the function shares the scope of the caller? For example, I was playing around with making a php version of the cold fusion tag CFPARAM What that cold fusion tag/sorta-function does is: 1) Check if a variable exists 2) If it doesn't, creat it with a default value
7
6053
by: ivan_oj28 | last post by:
Hi, I am developing an application where I need to read the caller id from an incoming call. The only info (for now) I need is the caller id info, so that I can display the propper caller info on screen if so desired. I was thinking on using asterisk (asterisk.org) for this with appropriate 2FXO/2FXS card but I do not know if this is just overkill (asterisk for this). Do you know of any other solution/way of getting the caller id and...
3
1431
by: Bryan | last post by:
I've been messing around with a C++ application on Xbox, and have been encountering problems with my objects getting garbage collected when they go out of scope, but before I'm actually done using them. I'm not really familiar with how this works in C++, since I first learned C, then Java, and never really spent a lot of time learning C++ other than applying Java concepts to C++'s syntax. Here's my problem: I have a function (doesn't...
7
1490
by: nick | last post by:
I have the following code: var ocevent = function(v) { alert('u clicked '+v); return false; }; var items = { "002.jpg": {text:"002", href:"#", click:function(){return
9
1656
by: Curious Student | last post by:
Some places till now, I've seen function prototypes within functions instead of in the global declaration space, which I thought was the way. I thought it was <I>only</I>: int myfunction(int, int); int main(void) {
6
4075
by: Maya | last post by:
Hello guys, in C#, is using "static" would be the most proper way to get around calling methods located in different classes? for instance, a method caller in class A wouldn't see a method in class B unless that method is declared as public static. This works fine (i guess!) for me, and i have been doing this for a long time, just came to my mind that there might be a better or more professional way to call methods in other classes...
33
11841
by: JamesB | last post by:
I am writing a service that monitors when a particular app is started. Works, but I need to get the user who is currently logged in, and of course Environment.UserName returns the service logon (NT_AUTHORITY\SYSTEM). I understand that when the service starts, no user may be logged in, but that's ok, as the app I am monitoring can only be run by a logged in user. Do I need to use WMI to get the user context of Explorer.exe or is there a...
9
215
by: Tim H | last post by:
class Foo {}; template <typename Tdata> const Foo &operator<<(const Foo &foo, const Tdata &data) { std::cout << "FOO: " << data << std::endl; } Foo
0
8337
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
8851
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
8748
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8531
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8628
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
7359
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
5650
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();...
1
2754
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
1739
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.