2012-11-26 74 views
2
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可能变得可变ab是否有可能在JavaScript中的父类中获取元素?

小提琴文件是在这里:http://jsfiddle.net/vTUqc/5/

+0

没有

function A() { this.a = 'this is a'; var b = 'this is b'; this.returnb = function(){ return b; } } 

现在b是的A实例访问...'了'和'B'是本地到那些功能。 –

+0

@FelixKling这只是一半。 'A'的任何实例都可以访问'a',而'B'的原型恰好是'A'的实例。 –

+0

@Asad:啊,我扫描的代码太快了,我的意思是'b'。 –

回答

1

你可以在Ba,使用this.a,因为B原型是A一个实例。您也可以在aC,使用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直接。如果您要访问它,你可以使用它的返回值的函数:通过(new A()).returnb()

+0

所以'b'在任何情况下都无法访问?像父类中的私有元素不能在C++的子类中访问? – Ovilia

+0

@Ovilia是的,有点类似于此。然而,你可以创建一个可以访问你的变量的方法。 –

+0

@Ovilia我已将此添加到答案 –

相关问题