如何将调用委派给包装对象 - 除了我更改的功能:
class Base {
doSomething() {}
doOtherSomething() {}
doOtherSomething2() {}
}
class Decorator {
constructor(wrapped) {
this.wrapped = wrapped;
}
doSomething() {
console.log("doing more stuff");
this.wrapped.doSomething()}
}
}
如何委托其他函数在基类上自动调用?
答案 0 :(得分:0)
假设您说的是一般意义上的包装(而不是几年来的各种装饰器提案),最简单的方法是根本不使用包装器。相反,要么:
#2 看起来像这样:
function wrapDoSomething(obj) {
const original = obj.doSomething;
obj.doSomething = function(...args) {
// Do something here, then:
return original.apply(this, args);
};
return obj; // Optional/nice to have
}
现场示例:
class Base {
doSomething() {
console.log("Original doSomething");
}
doOtherSomething() {
console.log("Original doOtherSomething");
}
doOtherSomething2() {}
}
function wrapDoSomething(obj) {
const original = obj.doSomething;
obj.doSomething = function(...args) {
console.log("wrapper doSomething - doing something before");
const result = original.apply(this, args);
console.log("wrapper doSomething - doing something after");
return result;
};
return obj;
}
const b = wrapDoSomething(new Base());
b.doSomething();
b.doOtherSomething();