Javascript访问父公共变量

Javascript access parent public variable

本文关键字:变量 访问 Javascript      更新时间:2023-09-26

我正在尝试让子类访问父变量。有人能告诉我这个代码出了什么问题吗?

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

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

我所做的是在b的实例中创建一个名为cself变量。然后我通过从内部函数访问b中的self来创建闭包;在这种情况下为CCD_ 9。

错误:self不存在于函数b的作用域中。self只存在于a的作用域。请尝试分配this.c.parent = self(或用该值构造this.c(并从(new b()).p()作为this.part而不是

尝试:

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