我相信您无法观察到document.location
使用的原因Object.observe()
是因为document.location
返回类型的对象Location Object
(这是特殊的只读接口)而不是“标准”对象。
来自 Mozilla 文档:
Document.location 只读属性返回一个 Location 对象。Document 对象的 location 属性引用 Location 对象。Window.location 是一个只读的 Location 对象。
位置接口:
https ://developer.mozilla.org/en-US/docs/Web/API/Location
例子:
console.log(document.location.__proto__); // returns Location {}
console.log(window.location.__proto__); // returns Location {}
window.location === document.location // always true
Object.observe() 方法用于观察对象的变化。
例子:
var o = { name: ''};
Object.observe(o, function(changes){
changes.forEach(function(change) {
console.log(change.type, change.name, change.oldValue);
});
});
o.name = 'foo'; // name is being observed
看看他们的区别__proto__
console.log(document.location.__proto__); // returns Location {}
console.log(window.location.__proto__); // returns Location {}
console.log(o.__proto__); // returns Object {}
如果您测试一个对象在其原型链中是否具有构造函数的原型属性,则足够有趣:
console.log(document.location instanceof Object); // true
console.log(o instanceof Object); // true
代码示例:
var o = {
name: ''
};
Object.observe(o, function(changes) {
changes.forEach(function(change) {
console.log(change.type, change.name, change.oldValue);
});
});
o.name = 'foo';
console.log(document.location.__proto__); // returns Location {}
console.log(window.location.__proto__); // returns Location {}
console.log(o.__proto__); // returns Object {}
console.log(document.location instanceof Object); // true
console.log(o instanceof Object); // true