HTML and CSS Reference
In-Depth Information
Before entering the inner function we declare a variable called that , and set it to refer to
the this object (the object itself). Inside the inner function we then access the that variable
rather than the this variable.
So far we have seen two different definitions of the this variable. In both these cases this
was implicitly defined by the programming environment. It is also possible to explicitly
specify the object that should be used to represent this . In order to see this in action we will
define a new object that adds two properties together:
> adder = {
num1: 10,
num2: 20,
add: function() {
return this.num1+this.num2;
If we call the add method, the two properties will be added together and returned:
> adder.add()
As mentioned earlier, functions and methods are actually objects in JavaScript, and there-
fore they support their own methods. These are defined on Function.prototype , (so nat-
urally you can also add your own methods to functions). One of the methods Func-
tion.prototype supports is apply , which allows an alternative environment to be provided
for the this variable:
> adder.add.apply({num1:30,num2:40})
The parameter passed to apply is an object containing the appropriate properties required
by the function. This approach can be used to replace the value of this in standalone func-
tions and object methods.
Another method provided to Function.prototype is bind . Rather than executing the func-
tion using the object passed in as the environment, bind returns a new function that per-
manently binds the object passed in as the this variable for the function:
> add2 = adder.add.bind({num1:30,num2:40})
Search WWH ::

Custom Search