我正在尝试在javascript中设计一个易于扩展的表单系统,但是我遇到了一些问题.
想象一下一个网络表单,您可以在其中填写食谱,按顺序放置它们,然后提交给厨师做饭.然后,假设您有3类食谱:沙拉,开胃菜和主菜.显然,每个表单将具有不同数量的字段和不同的表单.
我正在尝试做的是有一个整体的表单管理器,基本上接受基类Recipes并调用它上面的各种东西,如.saveForm(),. fillForm()或createNewForm()但我想每个这些东西要在派生类中实现.
在Javascript中实现这个OO结构的最佳方法是什么?或者这不是正确的方法吗?在编写了一些代码后,我发现自己分配了自己的类型并不断进行手动类型检查,但这使得扩展更加困难.
这是我要做的:
var Class = function (Parent, props) {
var Child, F, i;
Child = function () {
if (Child.uber && Child.uber.hasOwnProperty("__construct")) {
Child.uber.__construct.apply(this, arguments);
}
if (Child.prototype.hasOwnProperty("__construct")) {
Child.prototype.__construct.apply(this, arguments);
}
};
Parent = Parent || Object;
F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.uber = Parent.prototype;
Child.prototype.constructor = Child;
for (i in props) {
if (props.hasOwnProperty(i)) {
Child.prototype[i] = props[i];
}
}
return Child;
};
var Recipe = Class(null, {
__construct: function (name) {
this.name = name;
},
getName: function () {
return this.name;
}
});
var Salad = Class(Recipe, {
__construct: function (name) {
this.name = name;
},
getName: function () {
var name = Salad.uber.getName.call(this);
return name;
}
});
Run Code Online (Sandbox Code Playgroud)
因此,在这个例子中,我们使用 Class 函数来伪造比 JavaScript 中通常可用的更加结构化的面向对象方法。
我们使用构造函数和示例方法定义 Recipe 类。然后我们创建 Salad 类,它继承 Recipe 类的属性和方法,然后重新定义 getName 方法。在该方法内部,我们使用静态属性来访问该方法的父类实现。
如果您想了解更多相关信息,此代码基于 Stoyan Stefanov 的“JavaScript 模式”中提供的示例。
| 归档时间: |
|
| 查看次数: |
1727 次 |
| 最近记录: |