【问题标题】:how to pass init parameter to base class in javascript如何在javascript中将init参数传递给基类
【发布时间】:2014-05-19 11:34:19
【问题描述】:

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

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

function Sub (string) {

}
Sub.prototype = new Base( );


var instance = new Sub ('blue' );

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

【问题讨论】:

标签: javascript oop inheritance


【解决方案1】:

只需调用Base 函数,像这样

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

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

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

另外,一个对象的原型应该只依赖于其他对象的原型,而不是其他对象。所以,你会想用普通的方式继承

Sub.prototype = Object.create(Base.prototype);

【讨论】:

  • 我应该把线放在哪里 ------- Sub.prototype = Object.create(Base.prototype); --------在上述情况下?
  • @user494461 而不是Sub.prototype = new Base( );
猜你喜欢
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-13
  • 2011-10-14
  • 1970-01-01
  • 1970-01-01
  • 2021-08-03
相关资源
最近更新 更多