抱歉,如果这个问题已经得到解答,但我自己找不到答案。
我想知道是否可以创建自定义函数初始值设定项?像这样的东西:
const newFunction = customFunction() { // Function code }
或者
customFunction newFunction() { // Function code }
因此,每当调用 newFunction 时,都可以围绕函数代码运行代码。像这样的东西:
customFunction = {
// Before code
console.log("Starting customFunction")
// Function code
this()
// After code
console.log("Ending customFunction")
}
newFunction()
我希望这是有道理的,并提前致谢:)
无法创建自定义初始化程序。然而,使用高阶装饰器函数可以轻松实现相同的效果:
function customFunction(otherFn) {
return function() {
// Before code
console.log("Starting customFunction");
// Function code
const result = otherFn.apply(this, arguments);
// After code
console.log("Ending customFunction");
return result;
}
}
const newFunction = customFunction(function() {
console.log("running newFunction()");
});
newFunction();
console.log("---------");
const obj = {
a: 40,
giveMeTheAnswer: customFunction(function(b) {
return `the answer is: ${this.a + b}`;
})
}
console.log(obj.giveMeTheAnswer(2));
.as-console-wrapper { max-height: 100% !important; }