美文网首页
《javascript设计模式与开发实践阅读笔记一》

《javascript设计模式与开发实践阅读笔记一》

作者: 午夜书琳 | 来源:发表于2018-11-21 23:41 被阅读0次

    1.多态
    含义:同一操作作用于不同的对象上面,可以产生不同的解释和不同的执行结果;
    核心思想:将“做什么”和“谁去做以及怎样去做”分离开来,也就是将“不变的事”和“可能改变的事物”分离开来;
    eg:
    “多态的代码”
    var makeSound = function( animal ){
    if( animal instanceof Duck ){
    console.log("嘎嘎嘎");
    }else if ( animal instanceof Chicken ){
    console.log("咯咯咯");
    }
    }
    var Duck = function(){};
    var Chicken = function(){};

    makeSound( new Duck() );// 嘎嘎嘎
    makeSound( new Chicken() );//咯咯咯

    “对象的多态性”
    var makeSound = function( animal ){
    animal.sound();
    };
    var Duck = function(){};
    Duck.prototype.sound = function(){
    console.log("嘎嘎嘎");
    };
    var Chicken = function(){};
    Chicken.prototype.sound = function(){
    console.log("咯咯咯");
    };
    makeSound( new Duck() );// 嘎嘎嘎
    makeSound( new Chicken() );//咯咯咯
    // 扩展
    var Dog = function(){};
    Dog.prototype.sound = function(){
    console.log("汪汪汪");
    };
    makeSound(new Dog() );//汪汪汪
    不用修改makeSound方法;
    =====
    静态语言用向上转型实现多态(比如继承),继承一个抽象对象,然后传参的时候传抽象对象,不具体到某个对象,其他对象继承抽象对象就行。
    eg:Duck Chicken都继承自Animal类型,然后makeSound方法接受Animal为参数而不是具体的Duck或者Chicken
    ======
    JavaScript动态语言,

    相关文章

      网友评论

          本文标题:《javascript设计模式与开发实践阅读笔记一》

          本文链接:https://www.haomeiwen.com/subject/xmohqqtx.html