Could someone give me an example of Duck Typing inheritance in Javascript? I'm exploring OO javascript and I've heard about duck typing but can't see any examples of it being used in javascript.
相关问题
- Is there a limit to how many levels you can nest i
- how to define constructor for Python's new Nam
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
The second link gives an example of a duck-typing-like pattern in js. Not saying I recommend doing this, but... well, you asked for it. ;)
Wikipedia - Duck typing
JavaScript Interfaces and Duck Typing
An example for duck typing in JavaScript are iterables. JavaScript has actually no type called
Iterable
, but it has a definition for an object, which is iterable.This is the requirement for duck typing. If an object implements a method, defined in an interface, the object can be used in places, where the interface type is accepted. For iterables this is the case in loops
and arrays
The rule of "Duck Typing" is
In a class-based object-oriented programming language (C++, for example) to make both objects look like a duck you must inherit their classes from a common "interface" class, so the compiler would let you call
duck
methods on them. That is called a strong typing.Now this is how it's done in Javascript:
See, the
check
function check whether the passed object looks like a duck (it checks appearance and its' ability to quack). We pass two different objects to it and it will returntrue
on both. Besides the appearance and quacking these may be completely different things, but IN THIS PARTICULARcheck
function they behave the same way (have a common interface), they both look like a "duck". We can call thequack
method on both objects (and who cares what they really are).