如何在javascript中将init参数传递给基类

时间:2014-05-19 11:34:20

标签: javascript oop inheritance

来自https://stackoverflow.com/a/2107571/494461

function Base (string ) {
  this.color = string;
}

function Sub (string) {

}
Sub.prototype = new Base( );


var instance = new Sub ('blue' );

如何将字符串变量提前传递给基类?

1 个答案:

答案 0 :(得分:2)

只需调用Base函数,就像这样

function Base (string) {
    this.color = string;
}

function Sub (string) {
    Base.call(this, string);
}

使用Function.prototype.call,您将当前对象设置为Base函数调用作为Sub中的当前对象。因此,Base实际上只会在color对象中创建Sub属性。

此外,Object的原型应该仅依赖于其他对象的原型,而不是其他对象的原型。所以,你想要以常用的方式继承

Sub.prototype = Object.create(Base.prototype);
相关问题