Javascript:如何使用"传统的OOP"

时间:2012-07-13 10:34:15

标签: javascript oop

我正在研究一个来自PHP的验证器库我想给验证提供一个类似的Validators和Constraints设置(值,对象由验证器根据所选约束进行验证)。

因此,制定约束我有以下问题:

约束都共享相同的属性,只是实现略有不同。

示例:

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. 如果仍然是好的实践,我怎么能实现上面描述的这种行为? 我需要查找哪些关键字?
  3. 此致

2 个答案:

答案 0 :(得分: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 :(得分:1)

如果您来自Java,.NET,C ++背景,Javascript可能会令人困惑。在JS中没有类的概念,一切都只是另一个对象。甚至函数(用于模拟类)本身也是对象。看看下面的文章,了解事情是如何运作的。

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

正如弗洛里安所说,你需要使用基于原型的编码来模拟继承。但就个人而言,这种风格每次使用时都会感到腥。

另一方面,作为OOP概念的继承有时是有问题的,并且在大多数常见用例中可能被证明是反模式。我的建议是让你找到实现相同构图的方法,这对于大多数场景来说可能是一种更好的编程风格。