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

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

4

1 回答 1

1

你可以进入aB使用this.a,因为原型B是 的实例A。您也可以a使用:Cself.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可以访问Avia的实例(new A()).returnb()

于 2012-11-26T07:18:03.130 回答