Prototype bug or feature?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • a.riser@web.de

    Prototype bug or feature?

    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:'va l_one'});
    },
    procede: function(){
    document.writel n(' this.location: "'+this.locatio n+'"<br />');
    this.array.each ( function( item ){
    document.writel n(' this.location: "'+this.locatio n+'"<br />');
    });
    document.writel n(' this.location: "'+this.locatio n+'"<br />');
    this.hasch.each ( function( item ){
    document.writel n(' this.location: "'+this.locatio n+'"<br />');
    });
    }
    });
    x = new Test();
    x.procede();

    I'm using of course Prototype 1.6.0.2.

    Greets, a.
  • Joost Diepenmaat

    #2
    Re: Prototype bug or feature?

    a.riser@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:Objec ts:Array:forEac h>

    array.forEach(c allback[, 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/

    Comment

    • a.riser@web.de

      #3
      Re: Prototype bug or feature?

      On 3 Mai, 19:13, Joost Diepenmaat <jo...@zeekat.n lwrote:
      <http://developer.mozilla.org/en/docs...avaScript_1.5_
      Reference:Objec ts:Array:forEac h>
      >
        array.forEach(c allback[, 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.writel n(' this.location: "'+this.locatio n+'"<br />');
      }, this);
      ...

      works as I would have expected without the second parameter.

      Comment

      • jdalton

        #4
        Re: Prototype bug or feature?

        In fact Prototype uses the Native Array#forEach when available:
        if (Object.isFunct ion(Array.proto type.forEach))
        Array.prototype ._each = Array.prototype .forEach;

        Also for future reference the Prototype user mailing list is here:


        - JDD

        Comment

        Working...