2

为什么我不能通过将其分配给另一个变量来克隆 javascript 中的函数?

例如:

var $ = document.getElementById;


使用尝试:

typeof $;  //--> "function"
$('nav');  //--> "TypeError: Illegal invocation"


我认为它只会复制该功能,并且仍然可以调用。有人可以解释为什么不吗?

4

1 回答 1

4

When just assigning document.getElementById to a variable you lose the this === document part which you'd usually have when calling it as a method of document. To avoid this, use .bind() to explicitly set the this context the function uses:

var $ = document.getElementById.bind(document);
于 2013-04-17T21:38:57.317 回答