[英]Javascript: Accessing superclass objects from nested class
a = new function() {
this.x=2;
B=function() {
this.y=super.x;
}
this.b=new B();
}
alert(a.b.y); // Expecting 2
In the above, there is a parse error in super
. 在上面,在
super
存在解析错误。 How can I access the value of x when defining the class B? 定义类B时如何访问x的值?
This works but i'm not sure that your code is correct 这有效,但我不确定您的代码是否正确
a = new function() {
var x=2;
B=function() {
this.y=x;
}
this.b=new B();
}
alert(a.b.y); //alerts 2
alert(a.x) //alert undefined becuase x is private
in any case there is no super
in javascript, if you read here you can see how you could implement inehritance in javascript through a uber method 无论如何,在javascript中都没有
super
,如果您在这里阅读,可以看到如何通过uber方法在javascript中实现惯性
Found the best way to do this is to pass 'this' as the parameter in the constructor of the nested class, like this - 发现执行此操作的最佳方法是在嵌套类的构造函数中将“ this”作为参数传递,如下所示:
a = new function() {
this.x=2;
B=function(sup) {
this.y=sup.x;
}
this.b=new B(this);
}
alert(a.b.y); // Displays 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.