function setName( n ){
this.name = n;
}
aPerson = {};
setName.call( aPerson, "Bob") // aPerson will be passed to setName as "this", aPerson now is "Bob"
// But if we call setName as the following
// Who will get the name?
setName( "Alice");
// The global root is passed to setName as "this"
// So, we just created a global variable.
name == "Alice" //
// Another example
var myObj = {};
myObj.value = 10;
myObj.myFunction = function(){
this.value = 100;
function inner(){
this.value = 10000;
}
inner();
}
myObj.myFunction();
// When myFunction is called, myObj is passed to it as "this",
// but when inner() is called inside myFunction, global root is
// passed to it as this.
// So, we polluted the global name space again!
console.log( myObj.value ); // 100
console.log( value ); // 10000
"Technology is nothing. What’s important is that you have a faith in people, that they’re basically good and smart, and if you give them tools, they’ll do wonderful things with them.” --- Steve Jobs
JavaScript: "this" is so flexible
A Java object has always "this", but a JavaScript object may have no "this". Only the function in JavaScript really care about "this", but we have no idea what "this" is when we define a function. We know it when we call the function.
Labels:
JavaScript