FYI, fastest way is #1 as you're avoiding creating a closure
altogether (just using Function#call internally).

On May 16, 10:35 am, "T.J. Crowder" <t...@crowdersoftware.com> wrote:
> Hi,
>
> I don't know that there's any one standard pattern, but here are a
> couple of the more common ones [here I'm assuming that the closure
> will actually do more than just this.bar()]:
>
> 1. Specifically when using Enumerable#each[1], it has this handy
> second parameter you can use to set the context (never hurts to read
> the docs!):
>
>     $R(1,2).each(function(item) {
>         this.bar();
>     }, this);
>
> But more generally with these sorts of binding things:
>
> 2. Use a variable set to 'this', to take advantage of the closure:
>
>     var self = this;
>     $R(1,2).each(function(item) {
>         self.bar();
>     });
>
> 3. If you're not already creating a closure, you don't have to
> introduce one, you can use Function#bind[2] instead (here I'm breaking
> from my earlier assumption and *only* calling this.bar, and again,
> #each provides a better way to do this):
>
>     $R(1,2).each(this.bar.bind(this));
>
> Some further references: [3][4][5]
>
> [1]http://prototypejs.org/api/enumerable/each
> [2]http://prototypejs.org/api/function/bind
> [3]http://blog.niftysnippets.org/2008/04/you-must-remember-this.html
> [4]http://www.alistapart.com/articles/getoutbindingsituations
> [5]http://proto-scripty.wikidot.com/prototype:tip-using-an-instance-meth...
>
> HTH,
> --
> T.J. Crowder
> tj / crowder software / com
> Independent Software Engineer, consulting services available
>
> On May 16, 2:21 am, jk <jk.lists.questi...@gmail.com> wrote:
>
> > Consider the code pasted below.  This will not work because the
> > anonymous function will be executed in 'each's scope.  I have a class
> > with a bunch of callbacks that depend on other methods.  Is there a
> > way to make this work?  Thanks. --JK
>
> > var test = new baz();
> > test.foo();
>
> > var baz = function(){
> >         this.foo = function(){
> >                 $R(1,2).each(function(item){
> >                         this.bar();
> >                 });
> >         }
>
> >         this.bar = function(){
> >                 alert('bar');
> >         }
>
> > }
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Prototype & script.aculo.us" group.
To post to this group, send email to prototype-scriptaculous@googlegroups.com
To unsubscribe from this group, send email to 
prototype-scriptaculous+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/prototype-scriptaculous?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to