为什么我不能在javascript中传递此功能?

时间:2016-02-04 16:08:39

标签: javascript

我无法将document.getElementById作为参数传递:

鉴于此HTML:

<div id="el"></div>

这个javascript:

var test = function(fn) {
  alert(fn("el"));
}
// This works
test(function(id){
  return document.getElementById(id);
});
// This fails
test(document.getElementById);

小提琴:
https://jsfiddle.net/joshcomley/tv7chn9q/

我得到一个&#34;未捕获的TypeError:非法调用&#34;例如,在Chrome中。

为什么会这样?

2 个答案:

答案 0 :(得分:2)

举个例子。

var item = "This is a global variable";

var thing = {
  item: "a value",
  findInThing: function(prop) {
    return this[prop];
  }
}

alert(thing.findInThing("item"));

function call(a_func) {
    return a_func("item"); 
}

alert(call(thing.findInThing));

函数内this的值取决于调用的上下文。

getElementById的上下文中删除后,您正在调用document

它没有参与DOM文档来查找元素,因此失败了。

你可以创建一个包装另一个函数的新函数,然后使用bind在特定的上下文中调用它:

var myGEBI = document.getElementById.bind(document);
test(myGEBI);

答案 1 :(得分:1)

document.getElementById需要使用文档作为上下文执行,您可以使用bind修复它:

test(document.getElementById.bind(document));

FIDDLE