简体   繁体   English

实例化对象中不存在作为属性的子类方法

[英]Subclass method as property doesn't exist in instantiated object

I'm writing a State Pattern, and the methods that are properties of the different states that I have written as subclasses don't seem to exist in the instantiated State object.我正在编写一个状态模式,并且作为我作为子类编写的不同状态的属性的方法似乎不存在于实例化的状态对象中。

Help?帮助?

The part of the code that doesn't work is something like this:代码不起作用的部分是这样的:

var Main,
    Active,
    Inactive;

Main = (function() {
  function Main() {
    // Construct Main object
    this.currentStatus = new Inactive();
  }
  return Main;

})();

Active = (function() {
  function Active() {
    // Construct Active object
  }
  Active.prototype.deactivate = function() {
    // Deactivate
  }
  Active.prototype.activate = function() {
    // Do nothing
  }
  return Active;
})();
Active.prototype = Object.create(Main.prototype);
Active.prototype.constructor = Active;

Inactive = (function() {
  function Inactive() {
    // Construct Inactive object
  }
  Inactive.prototype.deactivate = function() {
    // Do nothing
  }
  Inactive.prototype.activate = function() {
    // Activate
  }
  return Inactive;
})();
Inactive.prototype = Object.create(Main.prototype);
Inactive.prototype.constructor = Inactive;

var object = new Main();

// This doesn't work
object.currentStatus.activate;

There is no activate method in object.currentStatus because you are reassigning Inactive.prototype on line 41. You need to do this before extending the prototype with more methods: object.currentStatus没有activate方法,因为您在第 41 行重新分配了Inactive.prototype 。您需要使用更多方法扩展原型之前执行此操作:

Inactive = (function() {
  function Inactive() {
    // Construct Inactive object
  }

  Inactive.prototype = Object.create(Main.prototype);
  Inactive.prototype.constructor = Inactive;

  Inactive.prototype.deactivate = function() {
    // Do nothing
  }
  Inactive.prototype.activate = function() {
    // Activate
  }
  return Inactive;
})();

Demo: http://jsbin.com/beqofigihu/edit?js,console演示: http : //jsbin.com/beqofigihu/edit?js,console

Same is true for Active class. Active类也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM