【问题标题】:Static function inheritance静态函数继承
【发布时间】:2017-04-21 20:49:04
【问题描述】:

我在Node.js 中为我的路线创建了一些Controllers 类,我希望它们能够在单例的基础上工作(不是必需的,这是额外的)

主控制器类

class RouteController {

    static getInstance() {
        if (!RouteController.singleton) {
            RouteController.singleton = new RouteController();
        }

        return RouteController.singleton;
    }
}

现在我想创建一个路由,例如查看帖子,我希望该类也具有单例模式,但不是 cop

PostController 类

class PostController extends RouteController {

}

如果我这样做并检查它console.log(RouteController.getInstance() === PostController.getInstance()),当我希望每个(子)类都有自己的单例实例时,它会返回true

我怎样才能正确地做到这一点?

【问题讨论】:

    标签: javascript node.js class static ecmascript-6


    【解决方案1】:

    一种简单的方法是查看您的singleton 属性是否是this 的实例。即使您在调用任何派生类之前调用​​RouteController.getInstance(),这也将起作用。

    class RouteController {
      log() {
        return 'Route';
      }
      static getInstance() {
        if (!(this.singleton instanceof this)) {
          // Only called twice so you can verify it's only initialized
          // once for each class
          console.log('Creating singleton...');
          this.singleton = new this();
        }
        return this.singleton;
      }
    }
    
    class PostController extends RouteController {
      log() {
        return 'Post';
      }
    }
    
    console.log(RouteController.getInstance().log());
    console.log(PostController.getInstance().log());
    console.log(RouteController.getInstance().log());
    console.log(PostController.getInstance().log());

    【讨论】:

      【解决方案2】:

      函数的正常规则适用。因此,您可以在函数内部使用this 来引用调用该方法的对象(在这种情况下是构造函数本身):

      class RouteController {
      
          static getInstance() {
              if (!this.singleton) {
                  this.singleton = new this();
              }
      
              return this.singleton;
          }
      }
      

      但是,如果直接调用RouteController.getInstance(),这仍然不起作用,因为所有子类都继承了静态singleton 属性,导致每个子类的!this.singleton 测试失败。

      有多种方法可以解决这个问题。一种是使用getOwnProperty 而不是直接访问它:

      if (!this.getOwnProperty('singleton')) {
      
      }
      

      【讨论】:

      • 我认为您无法在静态方法中访问 this,是吗?
      • @RobM.:每个函数都有一个 this 值(箭头函数除外)。如果你做RouteController.getInstance()this 指的是RouteController。普通的 JavaScript,这里没有什么神奇的。毕竟,静态方法只是函数对象的属性。 (function RouteController() {}; RouteController.getInstance = function() {})。
      • 我应该改写一下,我知道会有一个this 值,我只是不知道它会在静态方法中引用类本身,对此我有点惊讶。很高兴知道,谢谢!
      • @RobM.:当然取决于方法的调用方式,但如果您按预期执行Foo.bar()this 将引用Foo
      • 就像@FelixKling 所说,this 是可用的,但不,它不起作用。 console.log("PostController singleton", PostController.getInstance()); 在控制台中显示以下内容:PostController singleton RouteController {}
      猜你喜欢
      • 1970-01-01
      • 2013-05-09
      • 2014-06-26
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多