如何在不在子类的所有实例之间共享超类的相同实例的情况下在JavaScript中进行继承?

mta*_*nti 6 javascript prototype-oriented prototype-programming

我注意到每个关于如何进行JavaScript继承的教程都是这样做的:

SubClass.prototype = new SuperClass();
Run Code Online (Sandbox Code Playgroud)

但是这将创建超类的单个实例并在子类的所有实例之间共享它.

问题是我想将参数传递给超类构造函数,该构造函数源自传递给子类的参数.

在Java中,这将是这样做的:

class SubClass extends SuperClass {
  public SubClass(String s) {
    super(s);
  }
}
Run Code Online (Sandbox Code Playgroud)

我尝试过这样的事情:

function SubClass(args) {
  this.constructor.prototype = new SuperClass(args);
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用.那么在JavaScript中有没有办法做到这一点?

Fel*_*ing 5

常见的模式如下:

创建一个临时构造函数,它继承自父构造函数的原型.然后将子构造函数的原型设置为临时构造函数的实例.

function inherits(Child, Parent) {
    var Tmp = function() {};
    Tmp.prototype = Parent.prototype;
    Child.prototype = new Tmp();
    Child.prototype.constructor = Child;
}
Run Code Online (Sandbox Code Playgroud)

在子构造函数中,您必须调用父的构造函数:

function Child(a, b, c) {
    Parent.call(this, a, b);
}

inherits(Child, Parent);

// add prototype properties here
Run Code Online (Sandbox Code Playgroud)

在这个函数调用中,this将引用在调用时创建的新对象new Child(),因此,无论在内部执行什么初始化Parent,它都将应用于我们传递的新对象.


Lok*_*tar 2

我一直都是这样做的。

// Parent object
function Thing(options)
{ 
    //do stuff
}

Thing.prototype.someMethod = function(){
    // some stuff
   console.log('hello');
}

// child object which inherits from the parent
function OtherThing(options)
{       
    Thing.call(this, options);
    // do stuff for otherthing
}

OtherThing.prototype = new Thing();

OtherThing.prototype.someMethod = function(){
   // call things original function
   Thing.prototype.someMethod.call(this);

   // now do anything different
   console.log('other thing says hi');
}


var testObj = new OtherThing();
    testObj.someMethod();
Run Code Online (Sandbox Code Playgroud)

现场演示