zoukankan      html  css  js  c++  java
  • js中实现多态

    最近读到一本书《JavaScript设计模式与开发实践》上,讲到js的多态,我在JavaScript高级程序编程里貌似都没有见过关于这个的详细讲解,所以想问问大家有没有什么推荐的文章或者博客,可以推荐给小弟的,让小弟可以深入了解一下。
    先把那本上的例子拿出来跟大家分享:
    书里面的故事:本人家里养了一只鸡,一只鸭。当主人向他们发出‘叫’的命令时。鸭子会嘎嘎的叫,而鸡会咯咯的叫。转化成代码形式如下

    非多态代码示例

    var makeSound = function(animal) {
        if(animal instanceof Duck) {
            console.log('嘎嘎嘎');
        } else if (animal instanceof Chicken) {
            console.log('咯咯咯');
        }
    }
    var Duck = function(){}
    var Chiken = function() {};
    makeSound(new Chicken());
    makeSound(new Duck());

    多态的代码示例

    var makeSound = function(animal) {
        animal.sound();
    }

    var Duck = function(){}
    Duck.prototype.sound = function() {
        console.log('嘎嘎嘎')
    }
    var Chiken = function() {};
    Chiken.prototype.sound = function() {
        console.log('咯咯咯')
    }

    makeSound(new Chicken());
    makeSound(new Duck());

    附(https://segmentfault.com/q/1010000003056336)(http://blog.csdn.net/xiebaochun/article/details/38749953)

  • 相关阅读:
    Leetcode 349. Intersection of Two Arrays
    hdu 1016 Prime Ring Problem
    map 树木品种
    油田合并
    函数学习
    Leetcode 103. Binary Tree Zigzag Level Order Traversal
    Leetcode 102. Binary Tree Level Order Traversal
    Leetcode 101. Symmetric Tree
    poj 2524 Ubiquitous Religions(宗教信仰)
    pat 1009. 说反话 (20)
  • 原文地址:https://www.cnblogs.com/aliwa/p/6440945.html
Copyright © 2011-2022 走看看