Java Reference
In-Depth Information
var dist = distanceFromOrigin(new Point(0, 10));
print(dist);
// The above distanceFromOrigin() is the same as follows
var dist2 = origin.distance(new Point(0, 10));
print(dist2);
10
10
An important point about the Function() constructor is that the functions it creates
do not use lexical scoping; instead, they are always compiled as if they were top-level
functions. Listing 4-24 demonstrates this subtle point.
Listing 4-24. Testing the Captured Scoping of Functions Created by the Function Object
// functioncapture.js
var empId = 100; // Global
function createFunction1() {
var empId = 200; // Local
// Does not capture local empId
var test = new Function("print(empId)");
return test;
}
function createFunction2() {
var empId = 200; // Local
function test () {
print(empId); // Captures local empId
}
return test;
}
createFunction1()(); // Prints 100 (the global empId)
createFunction2()(); // Prints 200 (the local empId)
100
200
 
Search WWH ::




Custom Search