Javascript 检测类的静态和实例方法的参数和返回值
我试图记录一个名为的方法的输入参数和返回值Javascript 检测类的静态和实例方法的参数和返回值,javascript,class,instrumentation,Javascript,Class,Instrumentation,我试图记录一个名为的方法的输入参数和返回值 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
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:这不是一个家庭作业,我只是想为调试工具找到一个解决方案。您的问题是堆栈溢出错误,因为您正在重写自己的方法 也就是说
/*
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) /
}
// 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);
};
})