所以这很难。当直接调用一个方法时,this 指的是包含对象,而当从字符串转换调用时,this 指的是“window”(我相信,我仍然可能完全错了)。
谁能给我解释一下?
在第一个警告语句之后会发生 javascript 错误(这意味着直接调用可以很好地定义 _this
)
/**
* 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"});
我缺乏解释需要编辑:2/21/2012 9:56 AM(蒙大拿州)
所以问题是人造库 (UnderstandingThis.ui.Component1
) 包含一个使用 _this
的函数(设置为 this
) 并且在进行直接方法调用时工作正常。我的意思是在 javascript 中调用 UnderstandingThis.ui.Component1.performTask1()
。但是如果我通过字符串转换调用相同的任务 stStringToFunction("UnderstandingThis.ui.Component1.performTask1")()
_this
指的是 window
.但对我来说这没有意义。我只使用 javascript 1.5 年,这些细微差别(来自 Java/C#)很难理解。
最佳答案
如果你调用:
foo.bar()
然后在 bar
中,this
是 foo
。
如果你:
var baz = { bar: foo.bar };
baz.bar();
然后在bar
里面,this
就是baz
。
如果你要:
var bar = foo.bar;
bar();
那么在bar
里面,this
就是window
(因为它是默认对象)。
您的函数从其上下文中提取函数,然后调用它(因此 this
是 window
)。
关于Javascript 和这个错误。取决于函数的调用方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9381418/