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

JQuery, access root property of an object from within the nested property

本文关键字:属性 对象 访问 嵌套 JQuery      更新时间:2023-09-26

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

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;
            }
        }
    }
}

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

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

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

我想知道,有没有一种方法可以将"this"的范围向上移动以访问"validate_rule2"属性?

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

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

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

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