0

我正在开发一个来自 PHP 的验证器库,我想为验证提供一个类似的设置,包括验证器和约束(值、对象由验证器针对选定的约束进行验证)。

所以处理约束我有以下问题:

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

例子:

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. 如果它仍然是很好的实践,我该如何实现上述行为?我必须寻找哪些关键字?

问候

4

2 回答 2

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!"
于 2012-07-13T10:43:06.720 回答
1

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

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

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

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

于 2012-07-13T11:22:46.070 回答