[英]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
显然undefined
从Base
类中定义,换句话说,是Base
类的任何实例。
由于Sub
类没有覆盖从Base
类继承的hi
方法,因此在Sub
实例上调用hi
会回退到父实例,在这种情况下, this
显然是指Sub
类,因此是它的name
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.