HTML and CSS Reference
In-Depth Information
add: function(num2) {
this.num += num2;
return this.num;
}
}
This is a very simple object that contains a num property initialized to 10. It also exposes
an add method that adds the parameter passed in to this property and returns the result:
> obj.add(10)
20
> obj.add(10)
30
You will notice that this inside an object method refers not to the global window object,
but to the object itself.
Let's take this one step further:
> obj = { num: 10,
add: function(num2) {
helper = function(num2) {
this.num += num2;
return this.num;
}
return helper(num2);
}
}
In this example we are declaring a function inside the object's method. Although this is a
contrived example, the approach used here is common (especially for event listeners).
Intuitively it looks like this code should work: the helper function is using this.num to ac-
cess the num property on the object. Unfortunately this code does not work as expected:
> obj.add(20)
Search WWH ::




Custom Search