Hi,
In your example, `x` is in scope and will not be undefined within the
iterator, because the iterator function is a closure[1] over the
context containing `x`. The only reason `x` would be undefined would
be if you shadowed[2] it with a local declaration within your function
(either a var or a named function argument).
In that example, since your function is *already* a closure, there's
no particular need for `bind` anyway, just use a var pointing to
`this`:
var x = 1;
var array = [1,2,3,4];
var self = this; // or "me" is another popular name
array.each(function(num) {
if (num == x) {
// do something, involving "self"
}
});
Or, of course, just use the fact that `each` accepts a second
argument[3] defining what `this` should be:
var x = 1;
var array = [1,2,3,4];
array.each(function(num) {
if (num == x) {
// do something, involving "this"
}
},
this
);
`bind` is mostly useful when you're passing a function reference into
something that doesn't provide that second argument feature (like
`observe`) when you don't want to create a closure in the current
context.
There are, of course, many ways and it's down to the coder which they
prefer. :-)
[1] "Closures are not complicated"
http://blog.niftysnippets.org/2008/02/closures-are-not-complicated.html
[2] Variable shadowing
http://en.wikipedia.org/wiki/Variable_shadowing
[3] Enumerable#each
http://api.prototypejs.org/language/Enumerable/prototype/each/
HTH,
--
T.J. Crowder
Independent Software Engineer
tj / crowder software / com
www / crowder software / com
On Aug 11, 4:33 pm, kstubs <[email protected]> wrote:
> Well, and agreeably what I wrote seems a bit odd, however there are many
> cases when making "this" available to the anonomyous function is handy.
> What I have found, is when I bind "this", then you lose scope of the
> containing context. Take for example:
>
> var x = 1;
> vary array = [1,2,3,4];
>
> array.each(function(num) {
> if (num == x) { // x is out of scope, x is undefined
> // do something, involving "this"
> }.bind(this));
>
> So, to bind this, and pass the value of x, the argument order seems to be
> backwards.
--
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 [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/prototype-scriptaculous?hl=en.