tags:

views:

122

answers:

2

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.

+2  A: 

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

In computer programming with object-oriented programming languages, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface.

http://secure.wikimedia.org/wikipedia/en/wiki/Duck_typing

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.

http://blog.michaeleee.com/2008/02/javascript-interfaces-and-duck-typing.html

no
Brilliant, thanks for the replies. Now understanding I think i'm going to stick to my standard inheritance using the prototype chain.
elduderino
+1  A: 

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;  
}  

check(duck);  
check(someAnimal);  

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.

Knuckles