gpt4 book ai didi

javascript - 通过 ES6 Proxy 扩展方法可以工作,但出现 TypeError

转载 作者:行者123 更新时间:2023-12-01 01:49:40 25 4
gpt4 key购买 nike

通过 ES6 Proxy 实现扩展对象方法的函数可以工作,但出现 TypeError 如下:

const extendMethod = (obj) => (key) => (f) => {
const handler = {
get: (target, propKey, receiver) => {
const targetValue = Reflect.get(target, propKey, receiver);
return key === propKey
? f(target.valueOf())
: (typeof targetValue === "function")
? (...args) => Object(target.valueOf())[propKey](...args)
: targetValue;
}
};
return new Proxy(obj, handler);
};

const a = { x: 5 };
const f = (target) => { console.log(target); };
const a1 = extendMethod(a)("log")(f);
a1.log(); //{x:5}
//TypeError: a1.log is not a function

如何修改代码以避免错误?谢谢。

最佳答案

脚本需要 a1.log评估为函数,因为它继续被调用为 a1.log(); 。但随着线路

? f(target.valueOf())

f函数运行,调用 f 的输出然后返回到外部。但输出fundefined ,因为(外)f不返回任何内容。

抑制错误的一种方法是返回一个不执行任何操作的函数:

? (f(target.valueOf()), () => void 0)

const extendMethod = (obj) => (key) => (f) => {
const handler = {
get: (target, propKey, receiver) => {
const targetValue = Reflect.get(target, propKey, receiver);
return key === propKey
? (f(target.valueOf()), () => void 0)
: (typeof targetValue === "function")
? (...args) => Object(target.valueOf())[propKey](...args)
: targetValue;
}
};
return new Proxy(obj, handler);
};

const a = { x: 5 };
const f = (target) => { console.log(target); };
const a1 = extendMethod(a)("log")(f);
a1.log(); //{x:5}

或者您可以简单地访问a1.log属性(作为副作用调用该函数)而不调用它:

const extendMethod = (obj) => (key) => (f) => {
const handler = {
get: (target, propKey, receiver) => {
const targetValue = Reflect.get(target, propKey, receiver);
return key === propKey
? f(target.valueOf())
: (typeof targetValue === "function")
? (...args) => Object(target.valueOf())[propKey](...args)
: targetValue;
}
};
return new Proxy(obj, handler);
};

const a = { x: 5 };
const f = (target) => { console.log(target); };
const a1 = extendMethod(a)("log")(f);
a1.log; //{x:5}

如果外f function did 返回一个函数(也就是说,如果它是一个高阶函数),那么您将能够使用 a1.log()通常:

const extendMethod = (obj) => (key) => (f) => {
const handler = {
get: (target, propKey, receiver) => {
const targetValue = Reflect.get(target, propKey, receiver);
return key === propKey
? f(target.valueOf())
: (typeof targetValue === "function")
? (...args) => Object(target.valueOf())[propKey](...args)
: targetValue;
}
};
return new Proxy(obj, handler);
};

const a = { x: 5 };
const f = (target) => {
console.log(target);
return arg => {
console.log('inner fn! ' + arg);
};
};
const a1 = extendMethod(a)("log")(f);
a1.log('foo');

关于javascript - 通过 ES6 Proxy 扩展方法可以工作,但出现 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51647331/

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