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

Javascript基类如何访问派生类成员?,javascript,inheritance,prototype,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。子类中有一个属性名称

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函数中子类的name属性


这不违背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?
如何从基类访问子类的name属性 hi函数中的类

this
from
Base
类并不能真正访问
Sub
类的属性,
this.name
显然是
未定义的
from
Base
类,换句话说,
Base
类的任何实例


由于
Sub
类不重写从
Base
类继承的
hi
方法,因此在
Sub
实例上调用
hi
会返回到父实例,在该上下文中
明确引用
Sub
类,因此,它的
name
属性。

JavaScript不是一种纯粹的OOP语言。
Sub.prototype=newbase()也不是它是如何完成的<代码>对象。创建(Base.prototype)
以正确扩展。但是,如果你这样做的话,这应该很容易奏效。这会给出与问题中给出的结果相同的结果。根据,区别在于调用构造函数。这不应该对我的功能有影响,对吗?@Kiran是的,当然,但要做对。主要是因为这似乎更令人困惑,因为javascript不是OOP。它允许使用这些模式,但不是直接为之设计的。@DigiFriend:Kiran对OOP有着非常严重的误解。这个例子在爪哇、C++、C和GO中的工作原理完全相同。从父类继承的方法是“继承的”,因此可以访问当前类的
this
。它们不是由基类调用,而是由子类调用。事实上,即使说方法是由类调用的,也是对OOP的一种极端误解。方法由对象而不是类调用。