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

标签 javascript inheritance state-pattern

我正在编写一个状态模式,而作为子类编写的不同状态的属性的方法似乎不存在于实例化的 State 对象中。

帮忙?

代码中不起作用的部分是这样的:

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;

最佳答案

object.currentStatus 中没有 activate 方法,因为您要在第 41 行重新分配 Inactive.prototype。您需要执行此操作< em>在使用更多方法扩展原型(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;
})();

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

Active 类也是如此。

关于javascript - 实例化对象中不存在作为属性的子类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32562384/

相关文章:

java - 这个对方法的调用是如何在 java 的继承中解决的?

javascript - 为什么我的第二个函数调用阻止第一个函数执行?

javascript - jQuery slider 不会开始

c++ - 继承类的构造函数格式

c++ - 继承构造函数

c# - 使用 Entity Framework 持久化状态模式

javascript - Css3动态添加的元素没有得到动画

javascript - 使用 redux-form 7 将自定义 props 传递给组件

java - 状态设计模式: How to avoid code duplication when using entry() and exit()?

java - 状态模式中场注入(inject)的替代方案