Javascript访问父公共变量

时间:2014-05-16 17:40:12

标签: javascript class variables subclass

我正在尝试获取子类来访问父变量。有人能告诉我这段代码有什么问题吗?

function a() {
    this.val = 600;
    var self = this;

    this.c = new b();

    this.d = function() {
        console.log("P:");
        this.c.p();
    }
}

function b() {
    this.val2 = 1;
    this.p = function() {
        console.log(self.val);
    }
}

var test = new a();
test.d();

2 个答案:

答案 0 :(得分:1)

b函数中,self未定义,因为它不会创建闭包。这意味着您无法引用self

您编码的方式并不能创建闭包。

如果你这样做,那就有效:

http://jsfiddle.net/y2A93/

function a() {
    this.val = 600;
    var self = this;

    this.c = new b();
    this.c.self = self; // create `self` variable

    this.d = function() {
        console.log("P:");
        this.c.p();
    }
}

function b() {
    this.val2 = 1;
    this.p = function() {
        console.log(this.self.val); // create closure that passes `self` from `b` to `p`.
    }
}

var test = new a();
test.d();

我所做的是在名为self的{​​{1}}实例中创建一个b变量。我通过从内部函数访问c中的self来创建一个闭包;在这种情况下b

答案 1 :(得分:0)

错误:函数b的范围内不存在self。自我只存在于一个范围内。尝试分配this.c.parent = self(或使用该值构造this.c)并从中访问它 (new b()).p()为this.parent而不是

尝试:

function a() {
    this.val = 600;
    var self = this;

    this.c = new b(self);

    this.d = function() {
        console.log("P:");
        this.c.p();
    }
}

function b(parent) {
    this.val2 = 1;
    this.parent = parent;
    this.p = function() {
        console.log(this.parent.val);
    }
}

var test = new a();
test.d();