Javascript访问父公共变量
Javascript access parent public variable
我正在尝试让子类访问父变量。有人能告诉我这个代码出了什么问题吗?
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
的实例中创建一个名为c
的self
变量。然后我通过从内部函数访问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();
相关文章:
- 如何从字符串变量访问对象属性
- 无法使用变量访问数据 JSON
- D3:使用变量访问绑定数组中的对象
- JavaScript 变量访问错误
- CanvasJS-访问变量-访问属性toString的权限被拒绝
- 如何使用javascript数据对象?如何通过变量访问条目
- 如何使用变量访问对象属性
- 使用变量访问对象的属性
- 如何使用包含对象键名的变量访问对象属性
- 为什么通过缓存变量访问 DOM 更快
- 将 PHP 变量访问到外部 JavaScript 文件中
- 使用变量访问 Javascript 中的对象信息
- 使用变量访问 JSON 属性(字符串)
- 如何在 yii 中从 javascript 变量访问文本字段输入
- 如何使用 javascript 变量访问模型属性
- 根据 HighCharts 对象的变量访问数组的元素
- 使用动态变量访问 Meteor 中另一个变量的值
- 如何通过绑定的控制器变量访问服务的属性
- Angular JS工厂和变量访问
- 使用变量访问对象的值