HTML and CSS Reference
In-Depth Information
TestCase("CircleTest", {
"test should implicitly bind to object": function () {
assertEquals(12, circle.diameter());
The fact that this.radius is a reference to circle.radius inside
circle.diameter should not surprise you. The example in Listing 5.24 behaves
Listing 5.24 The this value is no longer the circle object
"test implicit binding to the global object": function () {
var myDiameter = circle.diameter;
// WARNING: Never ever rely on implicit globals
// This is just an example
radius = 2;
assertEquals(4, myDiameter());
This example reveals that it is the caller that decides the value of this . In fact,
this detail was left out in the previous discussion about the execution context. In
addition to creating the activation and variable objects, and appending to the scope
chain, the this value is also decided when entering an execution context. this
can be provided to a method either implicitly or explicitly.
5.4.1 Implicitly Setting this
this is set implicitly when calling a function using parentheses; calling it as a
function causes this to be set to the global object; calling it as a method causes
this to be the object through which the function is called. “Calling the function as
a method” should be understood as calling the function as a property of an object.
This is a highly useful feature, because it allows JavaScript objects to share function
objects and still have them execute on the right object.
For instance, to borrow array methods for the arguments object as discussed
previously, we can simply create a property on the object whose value is the method
we want to execute, and execute it through arguments , implicitly setting this
to arguments . Listing 5.25 shows such an example.
Search WWH ::

Custom Search