function A() {
this.a = 'this is a';
var b = 'this is b';
}
function B() {
var self = this;
this.c = 'this is c';
var d = 'this is d';
// a: undefined, b: undefined, c: this is c, d: this is d
$("#txt1").text('a: ' + A.a + ', b: ' + b + ', c: ' + this.c + ', d: ' + d);
C();
function C() {
// this.c is not defined here
// a: undefined, b: undefined, c: this is c, d: this is d
$("#txt2").text('a: ' + A.a + ', b: ' + b + ', c: ' + self.c + ', d: ' + d);
}
}
B.prototype = new A();
var b = new B();
B类和内部函数C是否可以获得变量a
和b
?
小提琴文件在这里:http://jsfiddle.net/vTUqc/5/
答案 0 :(得分:1)
您可以a
使用B
获取this.a
,因为B
的原型是A
的实例。您还可以使用a
C
中获取self.a
function A() {
this.a = 'this is a'; // This is accessible to any instance of A
var b = 'this is b'; // This is not accessible outside the scope of the function
}
function B() {
var self = this;
alert(this.a); // Alerts 'this is a'
C(); // Also alerts 'this is a'
function C() {
alert(self.a);
}
}
B.prototype = new A();
new B();
另一方面,你无法直接获得b
。如果要访问它,可以使用返回其值的函数:
function A() {
this.a = 'this is a';
var b = 'this is b';
this.returnb = function(){
return b;
}
}
现在b
可通过A
(new A()).returnb()
的实例