0

我们可以在 javascript 中创建对 document.location 属性的引用吗?从过去几天开始,我们正在研究在 document.createElement 上创建的钩子。在使用它时,我们怀疑是否可以在 document.location、document.scripts 等对象上创建挂钩。

var dbi = document.body.innerHTML; 
document.body.innerHTML=function () { 
    var elem = dbi.apply (document, arguments); 
    console.log(arguments); 
}
4

1 回答 1

3

在您的代码中:

> var dbi = document.body.innerHTML;

innerHTML是一个值为字符串的属性,因此分配给 dbi 的值是字符串原语。

> document.body.innerHTML=function () {

body 元素是一个宿主对象,没有理由相信您可以将函数对象分配给根据相关标准应该是字符串的属性。在某些环境中它可能是可能的,但它不能被依赖并且至少在某些正在使用的浏览器中会失败。

>     var elem = dbi.apply (document, arguments);

dbi是一个字符串原语,它没有应用方法。

>     console.log(arguments);
> }

编辑

在 ES5 中,您可以定义一个getter,例如

var o = {   
  get pageURI () {   
    return document.location.href;   
  }
} 

所以你可以这样做:

alert(o.pageURI);

document.location = document.location.href + '#foo';

alert(o.pageURI);  // current URI with #foo appended

但是你不应该在一般网络上依赖 ES5,许多浏览器还没有完全支持它。

于 2012-04-18T06:15:45.140 回答