【问题标题】:Can I return a function the same way as a getter does?我可以像 getter 一样返回一个函数吗?
【发布时间】:2019-04-02 04:51:01
【问题描述】:

我正在为 console.log() 编写一个包装器,以便我可以控制它何时运行。

当我使用 getter 时,我可以让它工作,但我想使用普通函数,以便我可以传递一些参数。

我希望它的功能与使用 getter 相同,因为它会在控制台中打印正确的类和行号。

当我使用 getter 时,正确的消息和类名以及行号会输出到控制台:

get info() {
        return console.info.bind(console);
}

调用者:

this.logger.info('this is a log');

控制台中的结果:

这是一个日志

当我使用函数时,控制台没有任何输出

public info() {
        return console.info.bind(console);
}

调用者:

this.logger.info('this is a log');

导致空白控制台:

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    当您使用函数时,它只是返回与您第一次调用时传递的 this 引用绑定的函数引用。

    所以你需要用参数再次调用返回的函数对象。作为一个例子,我在下面的 es6 类中做了同样的事情:

    class Test{
      info() {
         return console.info.bind(console);
      }
    }
    let test = new Test();
    test.info()("test");

    如果这需要一步完成,我们可以使用callapply 代替绑定。 callapply 立即调用函数,不像 bind 只会绑定 this 引用并返回绑定函数。

    对于使用call

    info(){
       return console.info.call(console, ...arguments);
    }
    

    apply:

    info(){
       return console.info.apply(console, arguments);
     }
    

    另一方面,当您使用 getter 时,访问像 info 这样的属性将导致调用 getter 并返回您正在调用的函数引用。 p>

    class Test{
      get info() {
          return console.info.bind(console);
      }
    }
    let test = new Test();
    test.info("test");
    test.info -> returns the function reference
    test.info("test") -> invokes the returned reference;
    

    【讨论】:

      【解决方案2】:
      public info() {
        return console.info.apply(console, arguments)
      }
      

      这样就可以了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-30
        • 1970-01-01
        • 1970-01-01
        • 2021-10-18
        • 1970-01-01
        • 2021-12-23
        • 1970-01-01
        相关资源
        最近更新 更多