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.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);
posted @   kkun  阅读(6301)  评论(3编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示