是否可以创建自定义函数初始值设定项?

问题描述 投票:0回答:1

抱歉,如果这个问题已经得到解答,但我自己找不到答案。

我想知道是否可以创建自定义函数初始值设定项?像这样的东西:

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()

我希望这是有道理的,并提前致谢:)

javascript function initialization initializer
1个回答
0
投票

无法创建自定义初始化程序。然而,使用高阶装饰器函数可以轻松实现相同的效果:

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; }

© www.soinside.com 2019 - 2024. All rights reserved.