2012-11-26 3 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에서 상위 클래스의 요소를 가져올 수 있습니까?

바이올린 파일은 여기에 있습니다 : B의 프로토 타입 A의 인스턴스이기 때문에 http://jsfiddle.net/vTUqc/5/

+0

없음 통해

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

이제 bA의 인스턴스에 액세스 할 수 ...'A'와': 당신이 그것을 액세스 할 경우에는 그 값을 반환하는 기능을 사용할 수 있습니다 그 기능들. –

+0

@FelixKling 그건 반쪽이에요. 'a'는'A'의 모든 인스턴스에서 접근 가능하고,'B'의 원형은'A'의 인스턴스가됩니다. –

+0

@Asad : 아, 코드를 너무 빠르게 스캔했는데, 나는 단지'b'를 의미했습니다. –

답변

1

당신은 this.a를 사용하여, B에서 a를 얻을 수 있습니다. 또한 self.a를 사용하여, Ca를 얻을 수 있습니다 :

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을 얻을 수 없습니다. 로컬 b` (new A()).returnb()

+0

그래서'b'는 어떤 경우에도 접근 할 수 없습니까? 부모 클래스의 개인 요소처럼 C++의 하위 클래스에서 액세스 할 수 없습니까? – Ovilia

+0

@Ovilia 예, 다소 유사합니다. 그러나 변수를 액세스 할 수있는 메소드를 만들 수 있습니다. –

+0

@Ovilia 답변에 다음을 추가했습니다 : –

관련 문제