2

我必须从子对象“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();

先感谢您 :-)

4

2 回答 2

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的范围

于 2013-06-15T08:44:34.870 回答
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);
        }
    };
}
于 2013-06-15T09:00:15.697 回答