使用不工作的窗口从字符串执行功能

时间:2014-08-06 22:51:26

标签: javascript string function

我尝试使用包含函数名称的字符串来执行函数。

Several resources I've found建议这样的内容:

function runMe(){alert("fail"));
var fnstring = "runMe";
var fn = window[fnstring];
fn();

然而,它对我来说根本不起作用(JSFiddle demo)。我最终以fn为未定义。我做错了什么,或者window行为发生了变化?

1 个答案:

答案 0 :(得分:1)

由于吊装,您收到Uncaught TypeError: undefined is not a function错误。查看您提供的第一个链接,您的版本与他们的版本之间存在一个关键区别:条件。

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();

你的版本抛出错误的原因是它被提升为这样的东西:

function runMe(thething) {
    alert("the function has successfully run: " + thething);
}

var fnstring, fn;

fn();

fnstring = "runMe";
fn = window[fnstring]("lkjlksdfsdfj");

所以当它被称为不是一个函数时;这是一个未定义的变量。

另一方面,据我了解吊装,我的版本会被提升:

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();

因此,当实际调用函数时,一切都很好。