我有一个代码,其中一个函数用于修改现有函数并返回一个新函数引用。我希望将该函数应用于类的特定方法。
我目前的代码是
function modifyMethod(func) {
return function() {
console.log('working');
return func.apply(this, arguments);
};
}
function modifyClassMethods(ClassName, methodArray) {
// The code goes here
return ClassName;
}
class Temp {
hi() {
console.log("hi method");
}
}
Temp = modifyClassMethods(Temp, ["hi"]);
const temp = new Temp();
// This should print
//
// working
// hi method
temp.hi();
当我尝试调用方法
modifyMethod
与 Temp.hi
, func
未定义。如果我创建一个对象然后修改该方法,那么新方法将仅应用于该特定对象的方法,而不应用于该特定类的所有对象。请注意,这只是一个示例。我想将此修改应用于多个类的方法。所以,我也不能概括方法名称。
modifyClassMethods
的任何代码片段会有帮助的。
最佳答案
class
正文中使用方法语法定义的方法未标记的构造 static
是原型(prototype)方法,所以它们位于 Temp.prototype
,而不是 Temp
本身。所以这就是你更新它们的地方:
Temp.prototype.hi = modifyMethod(Temp.prototype.hi);
只有静态方法在
Temp
上结束本身。您可能会看到在
class
中创建的其他函数正文使用 class fields proposal的语法:class Temp {
hi = () => {
//
};
}
这些是实例方法。它们由构造函数创建,并为每个实例重新创建,大致就好像它们是这样编写的:¹
class Temp {
constructor() {
this.hi = () => {
//
};
}
}
在创建实例之前/除非创建实例,否则您不能包装它们,因为它们是特定于实例的。
所以总结一下,考虑:
class Temp {
static staticMethod() {
// ...
}
prototypeMethod() {
// ...
}
instanceMethod = () => {
// ...
};
constructor() {
this.anotherInstanceMethod = () => {
// ...
};
this.yetAnotherInstanceMethod = function {
// ...
};
}
}
该类显示了三种类型的方法:
staticMethod
,您可以在 Temp
上找到它(例如,Temp.staticMethod
); prototypeMethod
,您可以在 Temp.prototype
上找到它(例如,Temp.prototype.prototypeMethod
);和 instanceMethod
, anotherInstanceMethod
, 和 yetAnotherInstanceMethod
,您可以在实例本身上找到它,如果/何时创建任何实例¹ 从技术上讲,它们是用
Object.defineProperty
创建的。像这样:class Temp {
constructor() {
Object.defineProperty(this, "hi", {
value: () => {
//
},
writable: true,
configurable: true,
enumerable: true
});
}
}
...不是通过简单的分配。我在示例中使用了简单的赋值来保持它......简单。 :-)
关于javascript - 获取类的函数引用(不是对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59498808/