繁体   English   中英

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

[英]Javascript how can base class access derived class member?

基类中有一个函数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的基本原理吗?

你误解了你所代表的例子。 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?

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

来自Base类的this并没有真正访问Sub类的属性, this.name显然undefinedBase类中定义,换句话说,是Base类的任何实例。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM