【问题标题】:Javascript Abstract Class with Object create带有对象创建的 Javascript 抽象类
【发布时间】:2017-12-13 03:33:00
【问题描述】:

这是我的抽象类:

var Animal = function(){
    this.name = ''
    this.legs = 0;
    throw new Error("cannot instantiate abstract class");
}
Animal.prototype.walk = function(){ console.log(this.name+ " walked")};

创建一个新的具体类:

var Dog = function(){} ;

现在我想创建一个具体的类 Dog 来继承抽象类 Animal。我尝试了以下两种方式。哪个是标准?:

Dog.prototype = Object.create(Animal.prototype)

或

Dog.prototype = Animal.prototype

我还尝试了var Dog = Object.create(Animal),这给了我一个错误。

【问题讨论】:

  • 扩展class 的标准方法是使用extends。
  • @str 如果你在 ES6 中可能,但 OP 似乎不是
  • 看看@这个链接可能会有所帮助coderwall.com/p/r47jlw/…
  • @smnbbrv 有 JavaScript 转译器。那么有理由不使用 ES6+ 吗?
  • ES6 听起来像是一个新标准。那么在 ES6 出现之前,开发者会做什么呢?

标签: javascript inheritance abstract-class


【解决方案1】:

在Animal 类中,您可以使if 检查当前constructor 是否为Animal,如果是则抛出错误。当您在Dog 中调用父构造函数并从原型继承时,您还需要将其构造函数指针设置为Dog。

var Animal = function() {
  this.name = ''
  this.legs = 0;
  if (this.constructor == Animal) {
    throw new Error("cannot instantiate abstract class");
  }
}
Animal.prototype.walk = function() {
  console.log(this.name + " walked")
};

function Dog() {
  Animal.call(this);
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

var inst = new Dog;
inst.name = 'lorem';
inst.walk()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 2012-11-27
    • 2017-04-10
    • 1970-01-01
    相关资源
    最近更新 更多