2012-11-26 75 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我已將此添加到答案 –

相關問題