【问题标题】:JQuery, access root property of an object from within the nested propertyJQuery,从嵌套属性中访问对象的根属性
【发布时间】:2016-01-12 11:09:04
【问题描述】:

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

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”属性?

【问题讨论】:

    标签: javascript jquery scope


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 我想这是我问的最接近的事情。感谢您的宝贵时间。
    猜你喜欢
    • 2012-11-12
    • 1970-01-01
    • 2016-07-13
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    相关资源
    最近更新 更多