Here’s the scenario: we have two objects:
It’s pretty simple to get Joe to greet Jill:
But how can we get Jill to greet Joe? She doesn’t have a greet method (and let’s assume we can’t / won’t / shouldn’t give her one). Well, because everything in JavaScript—including functions—is an object, everything can have a method, or a function that can be called from it. Functions are given two methods that allow you to call them in different contexts.
The context of a method is basically the object that will be this
when the function is called. In our greet
method, this
refers to the object joe
, because that’s what it is a part of.
Now, try this:
The call
method on JavaScript functions allows you to change the function’s context. The first parameter we pass in will be the new context: in this case, that’s jill
. Subsequent parameters are the parameters to the function you’re calling. In this case, “Joe” will be passed to greet
. If you run this, you’ll get an alert box with the message “Jill says hi to Joe.”
There’s also an apply
method; the only difference is that it takes the parameters of the method as an array, rather than as raw parameters, a la the call
method.
If you have a hard time remembering whether it’s call
or apply
that takes the array, remember that apply
and array both start with ”a.”
Thanks for reading!
聯(lián)系客服