So this is tough. When calling a method directly, this refers to the containing object while when calling from string conversion, this refers to “window” (i believe, i could still be completely wrong).
Could anyone explain this to me?
What will happen is a javascript error AFTER the first alert statement (that means direct call worked fine with how _this was defined)
/**
* converts a string to a function
*/
function stStringToFunction(string) {
var fnList = string.split(".");
var currentFn = window;
var nextFn;
while(currentFn !== undefined && (nextFn = fnList.shift())) {
currentFn = currentFn[nextFn];
}
return currentFn;
}
//An example library
UnderstandingThis.ui.Component1 = {
performTask1: function(options) {
var settings = {
opt1: true,
opt2: false
},
_this = this;
$.extend(settings, options);
_this._PrivateTask1(settings);
},
_PrivateTask1: function(settings) {
//Some sweet stuff here!
alert("Private task1: " + settings.from);
}
}
UnderstandingThis.ui.Component1.performTask1({from: "direct"});
stStringToFunction("UnderstandingThis.ui.Component1.performTask1")({from: "string-to-function"});
My lack of explanation required an edit: 2/21/2012 9:56 AM (Montana)
So the problem is that the faux library (UnderstandingThis.ui.Component1) contains a function that uses _this (which is set to this) and works fine when doing a direct method call. By that i mean in javascript calling UnderstandingThis.ui.Component1.performTask1(). But if i call this same task via a string conversion stStringToFunction("UnderstandingThis.ui.Component1.performTask1")() _this refers to window. But to me that does not make sense. I have only been doing javascript for 1.5 years and these little nuances (coming from Java/C#) are difficult to understand.
Your initial assertion:
is not really true. The
thispseudo-variable is bound based on the object reference used to get to the function (if any). If you instantiate a function as a property value of some object, and then call it by reference via that object property, then yes,thisis bound to that object. However, if you copy the function as a value to a property of another object, then a call via that other object will have that object asthis(it’s always a “Who’s on first?” issue when discussing this topic :-).In any case, you can use
.call()or.apply()to force thethisvalue to be whatever you want, regardless of how you get to the function. The bottom line is that in JavaScript there is never any inherent relationship between a function and any particular object. The binding ofthisis determined at every function call.