如何在一个对象上有效地应用许多不同的规则,以及使用javascript的面向对象技术

How to apply many different rules on an object efficiently and using object oriented techniques using javascript

本文关键字:技术 面向对象 javascript 规则 一个对象 有效地 应用 许多不      更新时间:2023-09-26

这是我第一次通过这个任务。我需要根据字段更新我的UI。字段可以是不同的类型。这里我只是检查一个备忘录或布尔类型。

// UI Field Rule set.    
var UIFieldRules = {
    isMemo: function() {            
        return this.DataType === DataTypeKVP("Memo");
    },
    isBoolean: function() {
         return this.DataType === DataTypeKVP("Boolean");
    },
    MapToList: function() {
        if (UIFieldRules.isMemo.call(this) || UIFieldRules.isBoolean.call(this)) {
            console.log("memo or bool");
            console.log(UIFieldRules.isMemo.call(this));
            console.log(this);
            MAPTOLIST_SELECTOR.prop('disabled', true);
            return;
        } else {
            MAPTOLIST_SELECTOR.prop('disabled', false);
            console.log("UI field rules found memo");
        }
    }
};

然后在加载所有字段时调用这个对象。

UIFieldRules.MapToList.call(field);

这很好地满足了任务,但是现在我需要在字段中应用更多的规则。(如果你以前听过这个,请打断我)

我怎么能得到这个集合,我可以只是添加一个规则到一个集合,并有他们都动态应用在javascript?

更新提供示例:

function MapToList(field){
    isBoolean:function(){}
    isMemo : function(){}
    execute : function(){
        if (UIFieldRules.isMemo.call(this) || UIFieldRules.isBoolean.call(this)) {
            console.log("memo or bool");
            console.log(UIFieldRules.isMemo.call(this));
            console.log(this);
            MAPTOLIST_SELECTOR.prop('disabled', true);
            return;
        } else {
            MAPTOLIST_SELECTOR.prop('disabled', false);
            console.log("UI field rules found memo");
        }
    }
}

然后,如果我想创建更多的规则(我做)我应该创建另一个对象像上面的一个吗?在JS中是否有这样做的最佳实践方法?

var rules = [];
rules.push(new MapToList(field));
rules.push(new RegExEnabled(field));
$.each(rules,function(item){
    item.execute();
});

您的示例方法非常好。创建实现相同接口的多个对象,将它们放在一个列表中,然后对每个对象调用一个公共方法:

var rules = [MapToList, RegExEnabled];
rules.forEach(function(item){
    item.execute(field);
});

然而,你可能想要注意,如果你的对象不是有状态的或者没有任何参数化,你通常不需要构造函数+ new,一个简单的对象字面量就足够了。
类似地,如果您的共享接口归结为单个execute方法,那么您实际上想要的不是对象列表,而是可以调用的函数列表。这不是Java:-)