zoukankan      html  css  js  c++  java
  • 《javascript设计模式与开放实践》学习(一)javascript实现多态1

    还是以鸭子唱歌为例

    1、prototype 给对象添加方法或属性

      <script>
            var makeSound=function (animal) {
                animal.sound();
            }
            var Duck=function () {
            }
            Duck.prototype.sound=function () {
                console.log("嘎嘎嘎");
            }
            var Chichen=function () {
            }
            Chichen.prototype.sound=function () {
                console.log("咯咯咯");
            }
            makeSound(new Chichen());
            makeSound(new Duck())
    
        </script>

    给定义的Duck和 Chicken添加sound的方法

    2、typeof和instanceof用法

    只有具有sound方法的动物才能唱歌

    1)typeof

    用来检测给定变量的数据类型,可能的返回值:

    1. 'undefined' --- 这个值未定义;

    2. 'boolean'    --- 这个值是布尔值;

    3. 'string'        --- 这个值是字符串;

    4. 'number'     --- 这个值是数值;

    5. 'object'       --- 这个值是对象或null;

    6. 'function'    --- 这个值是函数。

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

    2)instanceof用来判断对象是否某另一个对象的实力,返回值true or false

     var makeSound=function (animal) {
                if(animal.sound instanceof Function){
                    animal.sound();
                }
     }
    
    
    
  • 相关阅读:
    IDA 动态调试 ELF 文件
    双机调试环境搭建[win7+Windbg+VirtualKD]
    从域环境搭建到 MS14-068 提升为域权限
    栈溢出原理与 shellcode 开发
    Flask_0x05 大型程序结构
    rest-framework 框架的基本组件
    restful 规范
    Django的CBV和FBV
    Django-model 进阶
    Django-Ajax
  • 原文地址:https://www.cnblogs.com/GallopingSnail/p/5863356.html
Copyright © 2011-2022 走看看