我试图记录输入参数和方法调用的返回值。
class A {
constructor () {
this.x = 'x'
}
callinstance(x){
// i want to log above value of x without changing class code
if (typeof this.x !== 'string') throw new Error('this.x MUST_BE_STRING')
return x + 1
// i want to log value to be returned without changing code
}
}
A.callstatic = function(x){
// i want to log above value of x without changing class code
return x + 2
// i want to log value to be returned without changing code
}
A.a = 'a' // a static property should't be touched
// i can't change above code. i also cannot put a log in the actual methods
// now here is the soution, but runs into stack overflow. For obvious reasons.
const instrument = function(prop, static) {
return function (...args) {
if (!static) static = this
console.log(args) // here instrumenting inputs
const t = static[prop](...args)
console.log(t) // here instrumenting return values
return t
}
}
// overriding all the static methods
Object.getOwnPropertyNames(A).filter(p => typeof A[p] === 'function').forEach((prop) => {
A[prop] = instrument(prop, A)
})
// overriding all the instance methods
Object.getOwnPropertyNames(A.prototype).filter(p => typeof A.prototype[p] === 'function' && p !== 'constructor').forEach((prop) => {
A.prototype[prop] = instrument(prop)
})
// validation
console.log(A.callstatic(1))
console.log((new A()).callinstance(11))
console.log(A.a)
以上解决方案由于明显的原因而进入堆栈溢出。 有什么解决方法可以实现我的目标?无需更改班级代码?
PS:这不是家庭作业,我只是想知道一种调试工具的解决方案。
答案 0 :(得分:1)
您的问题是堆栈溢出错误,因为您要覆盖自己的方法 这意味着
/*
A[prop] = instrument(prop, A); <-- this turns into as followed (replacing A[prop] to method name)
function callinstance = () {
console.log(args) // here instrumenting inputs
const t = callinstance(...args) // <-- recursion happens here
console.log(t) /
}
您可以做一些变通办法来解决此问题,创建该函数的副本,并覆盖您的自定义函数中的类方法,请在 oldMethod
中调用// overriding all the static methods
Object.getOwnPropertyNames(A).filter(p => typeof A[p] === 'function').forEach((prop) => {
let oldMethod = A[prop];
A[prop] = function(args) {
console.log(args);
let x = oldMethod(args);
console.log(x);
};
})
// overriding all the instance methods
Object.getOwnPropertyNames(A.prototype).filter(p => typeof A.prototype[p] === 'function' && p !== 'constructor').forEach((prop) => {
let oldMethod = A.prototype[prop];
A.prototype[prop] = function(...args) {
console.log(...args);
let x = oldMethod.call(this, ...args);
console.log(x);
};
})