gpt4 book ai didi

javascript - 如何观察第三方对象的属性值变化?

转载 作者:行者123 更新时间:2023-12-05 00:37:03 25 4
gpt4 key购买 nike

我想观察何时更改第三方对象的属性。我正在采用分配自定义 setter 的方法,但我的 console.log下面永远不会被调用。这是为什么?有更好的方法吗?

const foo = { a: 1, b: 2 };

Object.assign(foo, {
set user(user) {
foo.user = user;
console.log(">>>>>> user was changed", user);
},
});

// Desired behaviour
foo.user = "asdf"; // >>>>>> user was changed asdf
delete foo.user; // >>>>>> user was changed undefined
foo.user = "asdf1" // >>>>>> user was changed asdf1
请注意,我需要变异 foo我无法将代理包装在 foo 周围并将其返回,因为它是一个第三方库,它会改变 .user内部

最佳答案

我找到了一种方法,虽然它很hacky

const foo = { a: 1, b: 2 };

let underlyingValue = foo.user

Object.defineProperty(foo, "user", {
get() {
return underlyingValue
},
set(user) {
underlyingValue = user;
console.log(">>>>>> user was changed", user);
},
enumerable: true
});

foo.user = "asdf";
console.log(foo)

我已经把它变成了下面的通用函数👇

/** Intercepts writes to any property of an object */
function observeProperty(obj, property, onChanged) {
const oldDescriptor = Object.getOwnPropertyDescriptor(obj, property);
let val = obj[property];
Object.defineProperty(obj, property, {
get() {
return val;
},
set(newVal) {
val = newVal;
onChanged(newVal);
},
enumerable: oldDescriptor?.enumerable,
configurable: oldDescriptor?.configurable,
});
}

// example usage 👇
const foo = { a: 1 };
observeProperty(foo, "a", (a) => {
console.log("a was changed to", a);
});
foo.a = 2; // a was changed to 2

Also available in typescript

🚨 Edit: This will break if the property is deleted eg delete foo.user. The observer will be removed and the callback will stop firing. You will need to re-attach it.

关于javascript - 如何观察第三方对象的属性值变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70152843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com