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