我试图在 JS
中实现类似 interface
的架构,如下在 C#
中。并遇到了绊脚石。这是代码示例:
// Interface for UIBuilder classes
function IUIBuilder() {
this.addUserToList = function () {
alert('parent: added');
};
}
// Class implementing the IUIBuilder
function ChatUIBuider() {
IUIBuilder.prototype.addUserToList = function () {
alert('child: added');
};
IUIBuilder.prototype.removeUserFromList = function () {
alert('child: removed');
};
return new IUIBuilder();
}
在第一个类中,我定义了一个方法 addUserToList
,我在第二个类 ChatUIBuider
中覆盖了它。还使用其原型(prototype)向基类添加了一种方法 removeUserFromList
。
我的问题是,addUserToList
方法仍然调用父类方法,即使它已在子类中被覆盖。为什么?
var builder = new ChatUIBuider();
builder.removeUserFromList(); // Invokes the child class method. - CORRECT
builder.addUserToList(); // Invokes the base class method- WHY??
谁能告诉我这是否是我的正确做法?
最佳答案
我建议这个结构:
function IUIBuilder() {
};
IUIBuilder.prototype.addUserToList = function () {
alert('parent: added');
};
// Class extending the IUIBuilder
function ChatUIBuider() {
}
ChatUIBuider.prototype = new IUIBuilder();
ChatUIBuider.prototype.addUserToList = function () {
alert('child: added');
};
ChatUIBuider.prototype.removeUserFromList = function () {
alert('child: removed');
};
ChatUIBuider 扩展了 IUIBuilder 并继承了它的功能,但覆盖了 addUserToList
功能。
在下面的代码中,将调用两个构造函数,但只会调用重写的 addUserToList
函数:
var chat = new ChatUIBuider();
chat.addUserToList();
关于javascript - 如何覆盖面向对象的 Javascript 中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13620781/