是否可以在JavaScript中获取父类中的元素?

时间:2012-11-26 07:15:15

标签: javascript inheritance

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/

1 个答案:

答案 0 :(得分:1)

您可以a使用B获取this.a,因为B的原型是A的实例。您还可以使用a

C中获取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。如果要访问它,可以使用返回其值的函数:

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

现在b可通过A

访问(new A()).returnb()的实例