问题描述
当我尝试为 document.getElementById
创建一个别名函数时,如下所示:
When I try to make an alias function for document.getElementById
as below:
f = document.getElementById;
但是,当我试着打电话时:
But, when I try to call:
var e_fullname = f("fullname");
它出现了错误:无法转换JavaScript参数
以下是好的:
var e_fullname = f.call(document, "funname");
你能告诉我原因吗?
推荐答案
调用函数有四种方法:
- 函数调用:
f(p1,p2)
- 方法调用:
obj.f(p1,p2)
- 应用或调用调用:
f.apply(obj,[p1,p2])
,f.call( obj,p1,p2)
- 构造函数调用:
new f(p1,p2)
- Function invocation:
f(p1, p2)
- Method invocation:
obj.f(p1, p2)
- Apply or Call invocation:
f.apply(obj, [p1, p2])
,f.call(obj, p1, p2)
- Constructor invocation:
new f(p1, p2)
在所有这些情况下, f
只是函数对象的引用(指针) (具有 [[Call]]
内部属性的对象。在所有这些情况下它的行为不同的是调用函数的方式,这很重要。
In all these cases, f
is just a reference (pointer) to a function object (an object with a [[Call]]
internal property). What makes it behave different in all these cases is the way the function is called, and that matters a lot.
所以, f
只是对 getElementById
对象的引用, document.getElementById
和<$ c之间没有区别$ C> someOtherHTMLElement.getElementById ;该函数不会阻止对引用它的对象的引用。
So, f
is just a reference to the getElementById
object, there's no difference between document.getElementById
and someOtherHTMLElement.getElementById
; the function doesn't hold back a reference to the object that references it.
如果要绑定某个owner对象,使用 bind
方法:
If you want to bind a certain "owner" object, use the bind
method:
var f = document.getElementById.bind(document);
这篇关于javascript中的别名功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!