调用类向后变量 (JavaScript)

Call class backward variable (JavaScript)

本文关键字:JavaScript 变量 调用      更新时间:2023-09-26

我有这个休耕代码:

the_class = {
 second_class : {
  third_class : {
   first_variable_name : "third class first variable",
   fourth_class : {
    first_variable_name : "forth class first variable",
    first_function_name : function()
    {
    var out = "";
    out += the_class.second_class.third_class.first_variable_name + "'n";
    out += this.first_variable_name + "'n";
    return out;
    }
   }
  }
 }
}
result = the_class.second_class.third_class.fourth_class.first_function_name();
alert(result);

结果:

third class first variable
forth class first variable

我需要在较低类位置的调用类变量。所以我使用:the_class.second_class.three_class.first_variable_name,但这是长!:(

有什么选项可以像这样调用反向类位置吗?我尝试了back.first_variable_name,backward.first_variable_name,没有人工作......:(

与文档中相同:../../../folder_name/file_name.txt

您可以添加对每个对象的父对象的引用。这将允许您执行所需的操作:

Myfourthclass = function(parentobj) {
    this.parent = parentobj;
    this.first_variable_name = "forth class first variable";
    
    var _this = this;
    this.first_function_name = function(){
        return _this.parent.first_variable_name + "'n" +
            _this.first_variable_name + "'n";
    }
}
Mythirdclass = function(parentobj) {
    this.parent = parentobj;
    this.first_variable_name = "third class first variable";
    this.fourth_class = new Myfourthclass(this);
}
Mysecondclass = function(parentobj) {
    this.parent = parentobj;
    this.third_class = new Mythirdclass(this);
}
Myfirstclass = function(){
    this.second_class = new Mysecondclass(this);
}
newclass = new Myfirstclass();
alert(newclass.second_class.third_class.fourth_class.first_function_name());