代理窗口对象以检测更改 [英] Proxying window object to detect changes

查看:29
本文介绍了代理窗口对象以检测更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以代理 window 对象来检测变化吗?我尝试了以下但没有任何运气:

Can I proxy the window object to detect changes? I tried the following without any luck:

var handler = {
  get: function(target, property) {
    console.log("getting " + property + " for " + target);
    return target[property];
  },
  set: function(target, property, value, receiver) {
    console.log("setting " + property + " for " + target + " with value " + value);
    target[property] = value;
    return true;
  },
};
var p = new Proxy(window, handler);
setTimeout(() => {
  window.a = 10; // expecting a log, but nothing...
}, 3000);
setTimeout(() => {
  window.c = 20; // expecting a log, but nothing...
}, 4000);

推荐答案

您必须在较低的代码中引用 Proxy 实例,而不是 window:

You have to reference the Proxy instance in your lower code, not the window:

var handler = {
  get: function(target, property) {
    console.log("getting " + property + " for " + target);
    return target[property];
  },
  set: function(target, property, value, receiver) {
    console.log("setting " + property + " for " + target + " with value " + value);
    target[property] = value;
    return true;
  },
};
var p = new Proxy(window, handler);

setTimeout(() => {
  p.a = 10;    // <------------
}, 300);
setTimeout(() => {
  p.c = 20;    // <------------
}, 400);

如果您无法更改引用 window 的代码,您还可以将代理命名为 window(并将对真实窗口的引用保存在另一个变量中),但它的代码看起来很混乱.

If you can't change the code that references the window, you could also name the proxy window (and save a reference to the true window in another variable), but the code for that would look confusing.

如果它在一个独立的脚本文件中,上面的技巧将不起作用,你将无法使用 Proxy - 毕竟你不能重新定义 window 对象.如果您正在寻找对 window 上特定属性的更改,您可以使用 defineProperty 并让 setter 在分配给新值时用新值覆盖属性描述符:

If it's in a standalone script file, the above trick won't work, and you won't be able to use a Proxy - you can't redefine the window object, after all. If you're looking for a change for a specific property on window, you could use defineProperty and have the setter overwrite the property descriptor with the new value when it gets assigned to:

Object.defineProperty(window, 'a', {
  configurable: true,
  set(value) {
    console.log("setting with value " + value);
    Object.defineProperty(window, 'a', { value });
  }
});

setTimeout(() => {
  window.a = 10;
  console.log(window.a);
}, 300);

这篇关于代理窗口对象以检测更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆