javascript中的别名功能 [英] Alias function in javascript

查看:506
本文介绍了javascript中的别名功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如果Javascript具有一流的功能,为什么这不起作用?

当我尝试为 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");

你能告诉我原因吗?

推荐答案

调用函数有四种方法:


  1. 函数调用: f(p1,p2)

  2. 方法调用: obj.f(p1,p2)

  3. 应用或调用调用: f.apply(obj,[p1,p2]) f.call( obj,p1,p2)

  4. 构造函数调用: new f(p1,p2)

  1. Function invocation: f(p1, p2)
  2. Method invocation: obj.f(p1, p2)
  3. Apply or Call invocation: f.apply(obj, [p1, p2]), f.call(obj, p1, p2)
  4. 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中的别名功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆