Javascript:定义一个新原型,用 document.findId() 替换 document.getElementById()

Javascript: defining a new protorype that would replace document.getElementById() with document.findId()

我想做的是创建一个原型函数,它可以像 document.getElementById() 的较短版本一样使用;这看起来很奇怪: document.findId();此方法将 return 与我使用常规 getElementById() 时相同的值 假设我做过这样的事情:

Element.prototype.findId = function (value) {
   var element = document.getElementById(value);
   return element;
};

var something = document.findId('some_id');
alert('Id is: ' + something);

我知道这个例子行不通,但实现这个目标的好方法是什么?

你可以简单地复制函数。

document.findId = document.getElementById;

完整示例:

document.findId = document.getElementById;

document.findId('something').innerHTML = "<b>Hello, world!</b>";
<div id="something"></div>