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 が変数aとを取得することは可能bですか?

フィドルファイルはこちら: http://jsfiddle.net/vTUqc/5/

4

1 に答える 1

1

のプロトタイプは のインスタンスであるため、 を使用してaに入ることができます。を使用して入ることもできます:Bthis.aBAaCself.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;
    }
}

viabのインスタンスにアクセスできるようになりましたA(new A()).returnb()

于 2012-11-26T07:18:03.130 に答える