Skip to content

Instantly share code, notes, and snippets.

@mjhea0
Created June 19, 2017 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjhea0/da03a1f4abfaf15feff0122617dcd605 to your computer and use it in GitHub Desktop.
Save mjhea0/da03a1f4abfaf15feff0122617dcd605 to your computer and use it in GitHub Desktop.

Duck Typing

It doesn't matter if it's a duck as long as it behaves (properties and methods match) like a duck.

class Duck {
  constructor(name) {
    this.name = name
  }
  takeOff() {
    console.log(`${this.name} is taking off`)
  }
  fly() {
    console.log(`${this.name} is flying`)
  }
}

Instances:

> const myDuck = new Duck('Larry')
> myDuck.name
'Larry'
> myDuck.takeOff()
Larry is taking off
> myDuck.fly()
Larry is flying

> const myPlane = new Duck('Roger')
> myPlane2.name
'Roger'
> myPlane2.takeOff()
Roger is taking off
undefined
> myPlane2.fly()
Roger is flying

Issues:

  1. Inaccurate. Can lead to false positives.
  2. The object's methods and properties have to be over arbitraty. How do you get agreement from other developers?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment