Managing Scope Using Call, Apply, and Bind
Calls a function, with the specified arguments passed in
The first argument becomes
this, the rest are passed in as regular arguments.
Using call allows you to maintain the scope of
this accross methods. It works
Here we’re using prototypical inheritance to allow us to inheirit properties from
call allows us to invoke
Animal to initialize
it’s properties while maintaining the correct scope.
Calls a function, with the specified arguments passed in as an array
call, the first argument becomes
this. The rest of the args are
passed in as an array.
Creates a bound function with the same function body as the function it’s called on
bind, we actually get a reference to a new function. The first argument
this, and the rest are passed as regular arguments.
This is especially handy for event handlers.
These examples are fairly trivial, but they do serve to show that it’s possible
to manage scope without aliasing
this to something like
self. In a lot of
cases that can actually be pretty confusing. But, as with everything, use what
makes sense! This method may or may not work well for you, and that’s okay.