I thought this would be something I could easily google, but maybe I'm not asking the right question...
How do I set whatever "this" refers to in a given javascript function?
for example, like with most of jQuery's functions such as:
$(selector).each(function() {
//$(this) gives me access to whatever selector we're on
});
How do I write/call my own standalone functions that have an appropriate "this" reference when called? I use jQuery, so if there's a jQuery-specific way of doing it, that'd be ideal.
Use:
Where
that
is the object which you wantthis
in the function to be.jQuery uses a
.call(...)
method to assign the current node tothis
inside the function you pass as the parameter.EDIT:
Don't be afraid to look inside jQuery's code when you have a doubt, it's all in clear and well documented Javascript.
ie: the answer to this question is around line 574,
callback.call( object[ name ], name, object[ name ] ) === false
Javascripts
.call()
and.apply()
methods allow you to set the context for a function.Now you can call:
Which would alert
FOO
. The other way around, passingobj_b
would alertBAR!!
. The difference between.call()
and.apply()
is that.call()
takes a comma separated list if you're passing arguments to your function and.apply()
needs an array.Therefore, you can easily write a function
hook
by using theapply()
method. For instance, we want to add a feature to jQuerys.css()
method. We can store the original function reference, overwrite the function with custom code and call the stored function.Since the magic
arguments
object is an array like object, we can just pass it toapply()
. That way we guarantee, that all parameters are passed through to the original function.You can use the bind function to set the context of
this
within a function.