属性 的子类方法在实例化对象中不存在
Subclass method as property doesn't exist in instantiated object
我正在编写一个状态模式,作为我作为子类编写的不同状态的属性的方法似乎不存在于实例化的状态对象中。
帮忙?
代码中不起作用的部分是这样的:
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
。您需要在 before extending具有更多方法的原型:
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
class也是如此。
我正在编写一个状态模式,作为我作为子类编写的不同状态的属性的方法似乎不存在于实例化的状态对象中。
帮忙?
代码中不起作用的部分是这样的:
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
。您需要在 before extending具有更多方法的原型:
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
class也是如此。