Take the 2-minute tour ×

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.

share|improve this question
duck typing doesn't work so well in javascript- your object might quack like a floating point number, but it may be just as likely to quack like a string or a boolean. –  kennebec Jul 31 '10 at 22:32
stackoverflow.com/a/12763070/822138 has some good examples & discussion. –  sam Mar 5 '13 at 21:43
add comment

2 Answers

up vote 8 down vote accepted

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. ;)



The simplest approach is to define the contract informally and simply rely on the developers at each side of the interface to know what they are doing. Dave Thomas has given this approach the name of "duck typing" —if it walks like a duck and it quacks like a duck, then it is a duck. Similarly with our Shape interface, if it can compute an area and a perimeter, then it is a Shape.


share|improve this answer
Brilliant, thanks for the replies. Now understanding I think i'm going to stick to my standard inheritance using the prototype chain. –  Mike Rifgin Aug 1 '10 at 22:10
The js example in wikipedia, does not check for any "walks" and "quacks"!! Shouldn't that example be updated? –  eminemence Sep 7 '12 at 18:46
add comment

The rule of "Duck Typing" is: If it looks like a duck and quacks like a duck, then it's a duck. In C++ 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:

var duck = {  
    appearance: "feathers",  
    quack: function duck_quack(what) {  
        print(what + " quack-quack!");  
    color: "black"  

var someAnimal = {  
    appearance: "feathers",  
    quack: function animal_quack(what) {  
        print(what + " whoof-whoof!");  
    eyes: "yellow"  

function check(who) {  
    if ((who.appearance == "feathers") && (typeof who.quack == "function")) {  
        who.quack("I look like a duck!\n");  
        return true;  
    return false;  


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 return true on both. Besides the appearance and quacking these may be completely different things, but IN THIS PARTICULAR check function they behave the same way (have a common interface), they both look like a "duck". We can call the quack method on both objects.

share|improve this answer
add comment

Your Answer


