我有一个覆盖函数的装饰器:
function decorator(target, key, descriptor) {
descriptor.value = function() {
console.log('overridden')
}
}
现在我想在另一个函数中执行覆盖,因此我需要将其作为参数传递,以便我仍然可以替换该方法:
function decorator(target, key, descriptor) {
replaceMethod(descriptor.value)
}
function replaceMethod(originalMethod) {
originalMethod = function() {
console.log('overridden')
}
}
以某种方式可以这样做吗?
答案 0 :(得分:2)
这可能会满足您的目标:
function decorator(target, key, descriptor) {
replaceMethod(descriptor, 'value')
}
function replaceMethod(obj, prop) {
obj[prop] = function() {
console.log('overridden')
}
}
答案 1 :(得分:1)
这将有效:
function bark(target, key, descriptor) {
replaceWith(descriptor, function(msg){
console.log("Woof!");
});
return descriptor;
}
function replaceWith(descriptor, value){
descriptor.value = value;
}
class Animal {
@bark
greet(msg) {
console.log(msg);
}
}
new Animal().greet("Hello");