gpt4 book ai didi

JavaScript - 实例的复制方法

转载 作者:行者123 更新时间:2023-11-30 13:53:43 25 4
gpt4 key购买 nike

我想要复制类实例的所有属性/方法的可能性:

class A {
get prop1() { return 1; }
get prop2() { return 2; }

doStuff() {
return this.prop1 + this.prop2;
}
}

class B extends A {
get prop1() { return 5; }
}
class AWrapper {
constructor(a) {
// [1] Copy all methods/propertys of a
this.doStuff = () => a.doStuff() + 42;
}
}

const a = new A();
const b = new B();
const wA = new AWrapper(a);
const wB = new AWrapper(b);
console.log(a.prop1(), wA.prop1(), wB.prop1()); // 1, 1, 5
console.log(a.doStuff(), wA.doStuff()); // 3, 45

我可以手动复制每个方法/属性,但是[1] 是否有一个简单的命令,使得wA 具有与a 相同的签名?

最佳答案

通常,Proxy是使用 mixin 或装饰器时的首选工具:

class A {
get prop1() {
return 1;
}

get prop2() {
return 2;
}

doStuff() {
return this.prop1 + this.prop2;
}
}


class B extends A {
get prop1() {
return 5;
}
}


function decorate(target) {
let mixin = {
doStuff() {
return target.doStuff() + 42;
}
}

return new Proxy(target, {
get(_, prop) {
return (prop in mixin) ? mixin[prop] : target[prop];
}
});
}


const a = new A();
const b = new B();

const wA = decorate(a)
const wB = decorate(b)

console.log(a.prop1, wA.prop1, wB.prop1); // 1, 1, 5
console.log(a.doStuff(), wA.doStuff()); // 3, 45

关于JavaScript - 实例的复制方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57693622/

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