如何在Javascript中使用多态

swd*_*dev -1 javascript polymorphism inheritance

大多数语言对类使用单继承.这样做的模式相当明显(例如在下面的Swift代码中).我仍然试图在JavaScript中围绕模式来创建对象层次结构并重用类函数和覆盖类函数

class animal {
    func talk() {
        print ("?")
    }
}

class bird : animal {
    override func talk() {
        print("tweet tweet")
    }
    func fly() {
        print("flap flap")
    }
}

class parrot : bird {
    override func talk() {
        print("polly want a cracker")
    }
}

var a = animal()
var b = bird()
var p = parrot()

a.talk()  /// ?
b.talk()  /// tweet tweet
b.fly()   /// flap flap
p.talk()  /// polly want a cracker
p.fly()   /// flap flap
Run Code Online (Sandbox Code Playgroud)

我认为我的问题是Javascript代码看起来不像这样.什么是等效的Javascript代码,所以我可以找出模式?

Tha*_*you 7

你几乎回答了自己的问题.你只需要学习JavaScript的语法.

我认为我的问题是Javascript代码看起来不像这样.

  1. 如果一种语言看起来与另一种语言不同,那对你来说并不是一个"问题"

  2. 您提供的Swift代码在语法上非常接近您需要编写的JavaScript(ES6)来表示相同的类层次结构

class Animal {
  talk() {
    console.log('?')
  }
}

class Bird extends Animal {
  talk() {
    console.log('tweet tweet')
  }
  fly() {
    console.log('flap flap')
  }
}

class Parrot extends Bird {
  talk() {
    console.log('polly want a cracker')
  }
}

var a = new Animal()
var b = new Bird()
var p = new Parrot()

a.talk()
b.talk()
b.fly()
p.talk()
p.fly()
Run Code Online (Sandbox Code Playgroud)


如果要在ES5中设置"类"继承,可以执行此操作

// Animal "class"
function Animal() {}

// Animal methods
Animal.prototype.talk = function talk() {
  console.log('?')
}

// ------------------------------
// Bird "class"
function Bird() {
  // if you want to call the parent constructor, you can do that here
  // Animal.call(this, arg1, arg2, ... argN)
}

// Bird inherits from Animal
Bird.prototype = Object.create(Animal.prototype)
Bird.prototype.constructor = Bird

// Bird methods
Bird.prototype.talk = function() {
  console.log('tweet tweet')
}
Bird.prototype.fly = function() {
  console.log('flap flap')
}

// ------------------------------
// Parrot "class"
function Parrot() {
  // if you want to call the parent constructor, you can do that here
  // Bird.call(this, arg1, arg2, ... argN)
}

// Parrot inherits from Bird
Parrot.prototype = Object.create(Bird.prototype)
Parrot.prototype.constructor = Parrot

// Parrot methods
Parrot.prototype.talk = function() {
  console.log('polly want a cracker')
}

var a = new Animal()
var b = new Bird()
var p = new Parrot()

a.talk()
b.talk()
b.fly()
p.talk()
p.fly()
Run Code Online (Sandbox Code Playgroud)