zoukankan      html  css  js  c++  java
  • javascript中的封装,多态,继承

    封装Encapsulation

    如下代码,这就算是封装了

    (function (windows, undefined) {
        var i = 0;//相对外部环境来说,这里的i就算是封装了
    })(window, undefined);

    继承Inheritance

    (function (windows, undefined) {
        //父类
        function Person() { }
        Person.prototype.name = "name in Person";
     
        //子类
        function Student() { }
        Student.prototype = new Person();           //修复原型
        Student.prototype.constructor = Student;    //构造函数
        Student.prototype.supr = Person.prototype;  //父类
     
        //创建子类实例
        var stu = new Student();
        Student.prototype.age = 28;
        Student.prototype.supr.name = "name in Student instance";
     
        //打印子类成员及父类成员
        alert(stu.name); //name in Student instance
        alert(stu.supr.name); //name in Person
        alert(stu.age); //28
     
    })(window, undefined);

    多态Polymorphism

    有了继承,多态就好办了

    //这就是继承了
    (function (windows, undefined) {
        //父类
        function Person() { }
        Person.prototype.name = "name in Person";
        Person.prototype.learning = function () {
            alert("learning in Person")
        }
     
        //子类
        function Student() { }
        Student.prototype = new Person();           //修复原型
        Student.prototype.constructor = Student;    //构造函数
        Student.prototype.supr = Person.prototype;  //父类
        Student.prototype.learning = function () {
            alert("learning in Student");
        }
     
        //工人
        function Worker() { }
        Worker.prototype = new Person();           //修复原型
        Worker.prototype.constructor = Worker;    //构造函数
        Worker.prototype.supr = Person.prototype;  //父类
        Worker.prototype.learning = function () {
            alert("learning in Worker");
        }
     
        //工厂
        var personFactory = function (type) {
            switch (type) {
                case "Worker":
                    return new Worker();
                    break;
                case "Student":
                    return new Student();
                    break;
            }
            return new Person();
        }
     
        //客户端
        var person = personFactory("Student");
        person.learning(); //learning in Student
        person = personFactory("Worker");
        person.learning(); //learning in Worker
     
    })(window, undefined);
  • 相关阅读:
    Configuration Error <providerOption name="CompilerVersion" value="v3.5"/>
    destoon3.0 用户模板首页应用新模板无效不能立即刷新的解决方法
    改变kingcms默认拼音路径格式/修改kingcms拼音路径
    VB正则表达式
    kingcms 友情链接中 设置为推荐 取消推荐 设置为头条 取消头条,以及设置为up的bug
    kingcms5部分BUG修复和修改技巧
    SqlServer 函数 大全
    图文讲解NTFS和FAT32硬盘下 asp.net 生成word 错误: 80070005 和 错误:8000401a 的解决方法
    destoon3.0 后台公司模板 安装新模板提示“CSS文件不存在”及其解决方法
    asp.net报错:“System.NullReferenceException: 未将对象引用设置到对象的实例”
  • 原文地址:https://www.cnblogs.com/syf/p/2764086.html
Copyright © 2011-2022 走看看