Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
595 views
in Technique[技术] by (71.8m points)

oop - Duck Typing in Javascript

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The rule of "Duck Typing" is

If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.

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:

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!
");  
        return true;  
    }  
    return false;  
}  

check(duck);  // true
check(someAnimal);  // true

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 (and who cares what they really are).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...