gpt4 book ai didi

javascript - JavaScript : How to intercept an object for function enhancement, 修饰和委托(delegate)中的反射?

转载 作者:行者123 更新时间:2023-12-04 02:08:51 25 4
gpt4 key购买 nike

是否可以在不对对象本身进行任何修改的情况下创建对对象的函数调用的拦截器?

function intercept(obj) {    
???

function onFunctionCall(funcName, funcArgs) { ... }
}

var obj = {};
var interceptedObj = intercept(obj);

interceptedObj.someFunc(1, 2, 3);

这可以用来增强对象:

function onFunctionCall(funcName, funcArgs) {
if ('fn1' === funcName) {
return /* something */
}
if ('fn2' === funcName) {
return /* something */
}
throw new Error(`Function ${funcName} is not supported.`);
}

或者装饰调用:

function onFunctionCall(funcName, funcArgs) {
console.debug(`Function ${funcName} started.`);
const returnValue = obj[funcName].apply(obj, funcArgs);
console.debug(`Function ${funcName} finished.`);
return returnValue;
}

或委托(delegate):

const delegateObj = new ....

function onFunctionCall(funcName, funcArgs) {
return delegateObj[funcName].apply(delegate, funcArgs);
}

最佳答案

您可以使用 Proxy object :

function intercept(obj) {        
return new Proxy(obj, {
get: function(target, prop) {
return typeof target[prop] !== 'function'
? target[prop]
: (...args) => onFunctionCall(prop, args);
}
});

function onFunctionCall(funcName, funcArgs) {
console.debug(`Function '${funcName}' started.`);
const returnValue = obj[funcName].apply(obj, funcArgs);
console.debug(`Function '${funcName}' finished.`);
return returnValue;
}
}

var obj = {
attr0: 0,
attr1: 1,
attr2: null,
myfn1: (...args) => console.log('executing myfn1 with', args),
myfn2: async (...args) => console.log('executing myfn2 with', args)
};
var interceptedObj = intercept(obj);

console.log('ATTR0', interceptedObj.attr0) // 0
console.log('ATTR1', interceptedObj.attr1) // 1
console.log('ATTR2', interceptedObj.attr2) // null
console.log('ABC', interceptedObj.abc) // undefined

interceptedObj.myfn1(1, 2, 3);
interceptedObj.myfn2(1, 2, 3);

// Function 'myfn1' started.
// executing myfn1 with [ 1, 2, 3 ]
// Function 'myfn1' finished.
// Function 'myfn2' started.
// executing myfn2 with [ 1, 2, 3 ]
// Function 'myfn2' finished.

关于javascript - JavaScript : How to intercept an object for function enhancement, 修饰和委托(delegate)中的反射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55179461/

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