如何检测何时访问JavaScript对象变量? [英] How to detect when a JavaScript object variable is accessed?
本文介绍了如何检测何时访问JavaScript对象变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试调试一些javascript代码,我需要知道何时访问/运行对象上的特定变量。不是在它发生变化时,而是在脚本运行到特定变量时。
I'm trying to debug some javascript code and I need to know when a particular variable on an object is accessed/run. Not when it changes, but when the script runs to a particular variable.
有办法吗?
推荐答案
你可以用 Reflect.apply()
或 Proxy.handler()
const o = {
abc: function() {
return 123
},
def: function() {
return "456"
}
}
for (let [key, value] of Object.entries(o)) {
if (typeof value === "function") {
let fn = o[key];
Object.assign(o, {
[key]: function(...args) {
// do stuff
console.log(key + " proxy arguments:", args);
return Reflect.apply(fn, o, args);
}
})
}
}
console.log(o.abc(1, 2, 3), o.def(4, 5, 6));
const o = {
abc: function() {
return 123
},
def: function() {
return "456"
}
}
for (let [key, value] of Object.entries(o)) {
if (typeof value === "function") {
Object.assign(o, {
[key]: new Proxy(o[key], {
apply: function(o, thisArg, args) {
// do stuff
console.log(key + " proxy arguments:", args);
return args;
}
})
})
}
}
console.log(o.abc(1,2,3), o.def(4,5,6));
这篇关于如何检测何时访问JavaScript对象变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文