什么对象.getElementById()最初附加到?

Chr*_*ams 0 javascript

我想修改任何对象负责的原型 .getElementById()

我知道document没有原型,所以.getElementById()实际附加了什么对象?

编辑:所以结果文件确实有原型(谢谢凯文).我觉得很傻.

Kev*_*eid 7

document没有原型是错误的.

关于这个getElementById方法,我不知道说什么规格,但Safari和Firefox之间的位置不同,所以它应该被视为一个实现细节.不要依赖定义的位置.您始终可以直接覆盖它document.

也就是说,我调查并在Firefox 8.0上,该方法是在document原型上定义的:

? Object.getPrototypeOf(document).hasOwnProperty("getElementById")
? true
? Object.getPrototypeOf(document)
? [xpconnect wrapped native prototype]
Run Code Online (Sandbox Code Playgroud)

在Safari(也可能是Chrome和其他WebKit衍生产品)上,它是document原型的原型:

› document.hasOwnProperty("getElementById")
  false
› Object.getPrototypeOf(document).hasOwnProperty("getElementById")
  false
› Object.getPrototypeOf(Object.getPrototypeOf(document)).hasOwnProperty("getElementById")
  true
› Object.getPrototypeOf(document)
  HTMLDocumentPrototype
› Object.getPrototypeOf(Object.getPrototypeOf(document))
  DocumentPrototype 
Run Code Online (Sandbox Code Playgroud)

您可以使用浏览器的对象检查器进行自己的研究,以查找原型链,或使用Object.getPrototypeOfhasOwnProperty.


document.getElementById在保持原始文件的同时覆盖,请执行以下操作:

var originalGEID = document.getElementById;
document.getElementById = function (id) {
    ...
    var originalElement = originalGEID.call(document, id);
    ...
};
Run Code Online (Sandbox Code Playgroud)

请注意,无论原始方法在原型链中的位置如何,这都会起作用.