如何使用“this”关键字从子对象引用属性

时间:2013-06-15 08:43:06

标签: javascript class object reference this

我必须从子对象“object3”调用“object1”中的属性,但是此示例不起作用,因为“this”关键字在“object2”而不是“object1”中引用,你知道如何这样做?

function object1() {
   this.a = "hello world";

   this.object2 = function() {
      this.object3 = function() {
         alert(this.a); //prints "undefined"
      }
  };
}

尝试使用以下示例:

var obj1 = new object1();
var obj2 = new obj1.object2();
obj2.object3();

提前谢谢: - )

2 个答案:

答案 0 :(得分:1)

function object1() {
    this.a = "hello world";
    var self = this;
    this.object2 = function () {
        this.object3 = function () {
            alert(self.a); //prints "undefined"
        }
    };
}
var obj1 = new object1();
var obj2 = new obj1.object2();
obj2.object3();

您必须存储this对象,否则您将访问函数this范围的this.object3

答案 1 :(得分:0)

随着范围的变化,

this会发生变化。您需要为任何新范围保存this的引用:

function object1 () {
    var first_scope = this;
    this.a = "hello world";

    this.object2 = function() {
        var second_scope = this;

        this.object3 = function() {
            var third_scope = this;
            alert(first_scope.a);
        }
    };
}