2012-07-13 46 views
0

我正在研究一个来自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 

我知道想知道两件事:

  1. 首先,如果根本推荐使用这种编程风格,即使JavaScript是另一种语言,并且对此也太动态了?
  2. 如果仍然很好练习,我怎么能实现上面描述的行为? 我必须寻找什么关键词?

问候

+1

我建议学习* 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

回答

1

你需要把你的函数原型,如果你希望他们被继承。

另外,在ES3中,要继承的最干净的对象是函数。

例子:

function Constraint() {} 

Constraint.prototype = { 
    constructor: Constraint, 

    validate: function() { 
     console.log('Hello!'); 
    }, 

    message: 'Property required!' 
}; 

var RequiredConstraint = new Constraint(); 

RequiredConstraint.message; // "Property required!" 
RequiredConstraint.validate(); // "Hello!" 

// Now let's override it 
RequiredConstraint.validate = function() { 
    console.log('Hey!'); 
}; 
RequiredConstraint.validate(); // "Hey!" 
1

的JavaScript可能会造成混淆,如果你来自一个Java,.NET,C++背景。在JS中没有类的概念,一切都只是另一个对象。即使是用来模拟类的函数本身也是对象。看看下面的文章,了解事情如何在引擎盖下工作。

https://developer.mozilla.org/en/JavaScript/Guide/Inheritance_Revisited

正如弗洛里安说,你需要使用基于原型的编码来模拟继承。但对我个人而言,这种风格每次使用时都会感到腥意。另一方面,作为OOP概念的继承有时是可疑的,并且可能在大多数常见用例中被证明是反模式。我的建议是为你寻找实现与作曲相同的方法,这对于大多数场景来说可能是更好的编程风格。

+0

嘿,你说得对。Javascript看起来很像传统OOP背景中的“锅炉代码”,我认为强迫JavaScript进入已知范例并不是一个好主意。我会稍微查看JavaScript设计模式(组合),看看如何让代码更具可读性。我标记florians问题作为答案坚持严格的计算器约定:) – 2012-07-13 13:00:49

+1

@ dev.pus如果你想看到在JS中使用的模式,一个很好的链接是这一个:http://javascript.info/tutorial/oop-concepts – 2012-07-13 13:55:06