调用类后向变量(JavaScript)

时间:2015-03-11 17:19:20

标签: javascript class

我有这个令人遗憾的代码:

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.third_class.first_variable_name,但这很长! :(

我是否可以使用像this.variable这样的东西来调用后向类位置? 我试过back.first_variable_name,backward.first_variable_name,没有人工作...... :(

与文件相同:../../../ folder_name / file_name.txt

1 个答案:

答案 0 :(得分:0)

您可以添加对每个对象的父级的引用。这可以让你做你想做的事:

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());