[英]Executing function from string using window not working
I'm trying to execute a function using a string containing the functions name. 我正在尝试使用包含函数名称的字符串执行函数。
Several resources I've found suggest something like this: 我 发现的 一些 资源建议如下:
function runMe(){alert("fail"));
var fnstring = "runMe";
var fn = window[fnstring];
fn();
However, it doesn't work at all for me ( JSFiddle demo ). 但是,它对我根本不起作用( JSFiddle演示 )。 I end up with fn
as undefined. 我最终得到fn
为undefined。 Am I doing something wrong, or has window
behavior changed? 我是在做错什么,还是window
行为发生了变化?
You're getting the Uncaught TypeError: undefined is not a function
error because of hoisting. 您将收到Uncaught TypeError: undefined is not a function
由于提升, Uncaught TypeError: undefined is not a function
错误。 Looking at the first link you provided, there was one key difference between your version and theirs: the conditional. 查看您提供的第一个链接,您的版本与它们的版本之间有一个关键区别:有条件的。
Your (second) version : 您的(第二个)版本 :
function runMe(thething) {
alert("the function has successfully run: " + thething);
}
// function we want to run
var fnstring = "runMe";
alert("string: " + fnstring);
// find object
var fn = window[fnstring]("lkjlksdfsdfj");
alert("function: " + fn);
// is object a function?
alert("is function?: " + typeof fn === "function");
fn();
My version, working without errors : 我的版本,没有错误 :
function runMe(thething) {
console.log("the function has successfully run: " + thething);
}
// function we want to run
var fnstring = "runMe";
// find object
var fn = window[fnstring]("lkjlksdfsdfj");
// is object a function?
if (typeof fn === "function") fn();
The reason why your version throws an error is that it is being hoisted into something like this: 您的版本引发错误的原因是它已被吊起,如下所示:
function runMe(thething) {
alert("the function has successfully run: " + thething);
}
var fnstring, fn;
fn();
fnstring = "runMe";
fn = window[fnstring]("lkjlksdfsdfj");
So when it's called it isn't a function; 因此,当它被调用时,它不是一个函数。 it's an undefined variable. 这是一个未定义的变量。
On the other hand, as far as I understand hoisting, my version gets hoisted something like this: 另一方面,据我了解,我的版本也可以这样悬挂:
function runMe(thething) {
console.log("the function has successfully run: " + thething);
}
var fnstring, fn;
fnstring = = "runMe";
fn = window[fnstring]("lkjlksdfsdfj");
if (typeof fn === "function") fn();
So that by the time the function is actually called, everything's good to go. 这样,在实际调用该函数时,一切就很好了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.