【问题标题】:Can't replicate inbuilt function in javascript无法在 javascript 中复制内置函数
【发布时间】:2026-02-22 22:40:01
【问题描述】:

Why do built-in functions not have a prototype property?
我在上面的链接上看到了一个帖子,但它没有解决我的问题。

我能够复制一些内置对象,例如

var w=window;
w.alert("hi");
var d=document;
console.log(d.getElementById);

但我无法复制函数

var a=document.getElementById;
console.log(a);

原型被复制,但调用时它不起作用

var a=document.getElementById;
console.log(a('id'));

我用它来降低编码工作量。我知道我可以通过使用

来实现这一点

function a(id){
 return document.getElementById(id);
}
console.log(a('id'));

但这不是我想要的。有没有其他方法可以复制函数

【问题讨论】:

  • var a = document.getElementById.bind(document); 工作。
  • 与原型无关,但调用getElementById时的this必须设置为document。在第三个示例中,您还可以执行a.call(document, id)

标签: javascript function dom replication built-in


【解决方案1】:

@Xufox,这是有效的。非常感谢

var a = document.getElementById.bind(document);
console.log(a('id'));

【讨论】:

    最近更新 更多