javascript duck typing范例(转自http://stackoverflow.com/questions/3379529/duck-typing-in-javascript)

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值