Javascript如何基类访问派生类成员?

时间:2017-05-02 13:33:37

标签: javascript inheritance prototype

基类中有一个函数 hi 。子类中有一个属性名称

function Base() {}
Base.prototype.hi = function () {
    console.log("hi " + this.name);
}

function Sub(name) {
    this.name = name;
}
Sub.prototype = new Base();

mySub = new Sub("rohita");
mySub.hi();

输出

hi rohita

基类的如何能够从 hi 函数中的子类访问名称属性?

这不符合oops基础吗?

1 个答案:

答案 0 :(得分:0)

您误解了您所代表的示例。 Sub类的所有实例都具有name属性,相反,没有Base类实例可以访问name属性。

仔细看看:

mySub = new Sub("rohita");
mySub.hi();
// since Sub class doesn't override the hi method, it falls back to the parent's one,
// thus this.name is valid for any instances of Sub class.. not of Base class,
// Base class instances doesn't really access the name property of Sub class..
// to prove this let's log out `this.name` for any instance of Base class,
// it'll be simply `undefined`, but for the Sub class, it's the one already defined by Sub class itself

myBase = new Base();
myBase.hi(); // => hello undefined // makes sense now, right?

这是如何从基类中访问子类的name属性 函数中的类?

this类的

Base并没有真正访问Sub类的属性,显然this.nameundefined类的Base换句话说,Base类的任何实例。

由于Sub类不会覆盖从hi类继承的Base方法,因此在hi实例上调用Sub会退回到父实例,在这种情况下,this显然是指Sub类,因此它是name属性。

相关问题