JQuery,从嵌套属性中访问对象的root属性

时间:2016-01-12 11:09:04

标签: javascript jquery scope

我有一个列出一系列验证规则的对象,如下所示。

validation_rules = {
    'validate_rule1' : {
        'rule' : function(el){
            do something
            if(true){
                this.message = 'this is a numeric error';
            }
            return true;
        },
        'message' : 'this is a general error';
    },
    'validate_rule2' : {
        'rule' : function(el){
            do something
            return this.variation.variation_1(el);
        },
        'message' : 'this is a general error',
        'variation' : {
            'variation_1' : function(el){
                return true/false;
            }
        }
    }
}

该对象由执行规则的函数使用,以确定输入是否有效,并为每个失败的规则返回相应的消息。

我知道如何为每个规则设置默认消息,并使用实例“this”覆盖它,就像我在rule1中所做的那样。

我可以覆盖rule2的消息,将实例的每个变体作为函数的参数传递。

我想知道,有没有办法提升“this”的范围以访问“validate_rule2”属性?

1 个答案:

答案 0 :(得分:1)

您可以使用javascript call函数在调用函数variation_1时传递父级的范围,您可以传递您可能需要的任何范围。

fun.call(thisArg[, arg1[, arg2[, ...]]])

使用第一个参数,您可以设置函数的this对象

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/call

相关问题