我正在研究一个来自PHP的验证器库我想验证一个类似的设置与验证器和约束(值,对象得到验证器对验证选定的约束)。Javascript:如何使用“传统的OOP”
所以工作的限制,我有以下问题:
约束都有着相同的性质只是实现略有不同。
例子:
Constraint = Validator.Constraint = {
name: null, // contains the name of the constraint
value: null, // contains the value which we want to validate
options: {}, // contains options for some Constraints (e.g. range)
message: null, // contains the error message which is getting returned
validate: function(){}, // the validation logic
constructor: function(value, options){
this.value = value;
this.options = options;
this.validate();
} // the constructor which can be called for stand-alone validation
};
现在我想以某种方式延长约束和定制:
RequiredConstraint = Validator.RequiredConstraint = {
name: "required",
message: "this property is required",
validate: function(){
if (this.value != "" || this.value != undefined || this.value != null) {
return;
}
return this.message;
}
// other properties get inherited
};
的约束则应该使用具有:
RequiredConstraint("");
// returns false
我知道想知道两件事:
- 首先,如果根本推荐使用这种编程风格,即使JavaScript是另一种语言,并且对此也太动态了?
- 如果仍然很好练习,我怎么能实现上面描述的行为? 我必须寻找什么关键词?
问候
我建议学习* JavaScript方法*,即[原型继承](https://developer.mozilla.org/en/JavaScript/Guide/Inheritance_and_the_prototype_chain)。然后,当你获得更多的舒适时,了解[这些高级模式](http://addyosmani.com/resources/essentialjsdesignpatterns/book/)。对于这种特殊情况,我会说不要重新发明轮子并使用[我自己的插件](http://elclanrs.github.com/jq-idealforms/)来验证您的表单。 – elclanrs 2012-07-13 10:43:15