How about we characterize a basic protest, and make and occasion of it, as takes after:
var MyObject = function() {}
MyObject.prototype.whoAmI = function() {
console.log(this === window ? "window" : "MyObj");
};
var obj = new MyObject();Presently, for accommodation, we should make a reference to the whoAmI technique, probably so we can get to it simply by whoAmI() instead of the more obj.whoAmI():var whoAmI = obj.whoAmI;
What's more, just to make certain everything looks copacetic, how about we print out the estimation of our new whoAmI variable:console.log(whoAmI);
Yields/Output:
function () {
console.log(this === window ? "window" : "MyObj");
}
Alright, cool. Looks fine.
In any case, now, take a gander at the distinction when we summon obj.whoAmI() versus our accommodation reference whoAmI():
obj.whoAmI(); // outputs "MyObj" (as expected)
whoAmI(); // outputs "window" (uh-oh!)
What turned out badly?
The headfake here is that, when we did the task var whoAmI = obj.whoAmI;, the new factor whoAmI was being characterized in the worldwide namespace. Therefore, its estimation of this is window, not the obj occurrence of MyObject!
Accordingly, in the event that we truly need to make a reference to a current technique for a protest, we should make certain to do it inside that question's namespace, to protect the estimation of this. One method for doing this would be, for instance, as takes after:
var MyObject = function() {}
MyObject.prototype.whoAmI = function() {
console.log(this === window ? "window" : "MyObj");
};
var obj = new MyObject();
obj.w = obj.whoAmI; // still in the obj namespace
obj.whoAmI(); // outputs "MyObj" (as expected)
obj.w(); // outputs "MyObj" (as expected)
0 comments:
Post a Comment