By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,606 Members | 1,784 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,606 IT Pros & Developers. It's quick & easy.

Prototype bug or feature?

P: n/a
Hello

When using *this* in an Array#each or Hash#each-loop this references
*window*. Is this intentional (I can't believe it)? An example here:
http://www.banza.net/jstest/this.html .

The code there is:

var Test = Class.create({
initialize: function(){
this.location = '----------- eeehhhh ---------------';
this.array = $A([1])
this.hasch = $H({key_one:'val_one'});
},
procede: function(){
document.writeln(' this.location: "'+this.location+'"<br />');
this.array.each( function( item ){
document.writeln(' this.location: "'+this.location+'"<br />');
});
document.writeln(' this.location: "'+this.location+'"<br />');
this.hasch.each( function( item ){
document.writeln(' this.location: "'+this.location+'"<br />');
});
}
});
x = new Test();
x.procede();

I'm using of course Prototype 1.6.0.2.

Greets, a.
Jun 27 '08 #1
Share this Question
Share on Google+
3 Replies


P: n/a
a.*****@web.de writes:
Hello

When using *this* in an Array#each or Hash#each-loop this references
*window*. Is this intentional (I can't believe it)? An example here:
http://www.banza.net/jstest/this.html .
Dunno if it's intentional; I don't use Prototype, but it matches the
behaviour of Array.prototype.forEach in JavaScript 1.6:

<http://developer.mozilla.org/en/docs...avaScript_1.5_
Reference:Objects:Array:forEach>

array.forEach(callback[, thisObject]);

IOW, in JS 1.5 you must pass a second argument specifying the <<this>>
object, otherwise it'll be the global object (window).
--
Joost Diepenmaat | blog: http://joost.zeekat.nl/ | work: http://zeekat.nl/
Jun 27 '08 #2

P: n/a
On 3 Mai, 19:13, Joost Diepenmaat <jo...@zeekat.nlwrote:
<http://developer.mozilla.org/en/docs...avaScript_1.5_
Reference:Objects:Array:forEach>

* array.forEach(callback[, thisObject]);
Thank you, it's indeed the same in Prototype (now I found it in the
docs - shame on me):

...
this.hasch.each( function( item ){
document.writeln(' this.location: "'+this.location+'"<br />');
}, this);
...

works as I would have expected without the second parameter.

Jun 27 '08 #3

P: n/a
In fact Prototype uses the Native Array#forEach when available:
if (Object.isFunction(Array.prototype.forEach))
Array.prototype._each = Array.prototype.forEach;

Also for future reference the Prototype user mailing list is here:
http://groups.google.com/group/rubyonrails-spinoffs

- JDD
Jun 27 '08 #4

This discussion thread is closed

Replies have been disabled for this discussion.