博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaScript实现多态和继承的封装操作示例
阅读量:6887 次
发布时间:2019-06-27

本文共 1958 字,大约阅读时间需要 6 分钟。

hot3.png

封装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";  //打印子类成员及父类成员  console.log(stu.name); //name in Student instance  console.log(stu.supr.name); //name in Person  console.log(stu.age); //28})(window, undefined);

前端全栈学习交流圈:866109386,面向1-3经验年前端开发人员,帮助突破技术瓶颈,提升思维能力

运行结果如下: 多态Polymorphism

有了继承,多态就好办了

//这就是继承了(function (windows, undefined) {  //父类  function Person() { }  Person.prototype.name = "name in Person";  Person.prototype.learning = function () {    console.log("learning in Person")  }  //子类  function Student() { }  Student.prototype = new Person();      //修复原型  Student.prototype.constructor = Student;  //构造函数  Student.prototype.supr = Person.prototype; //父类  Student.prototype.learning = function () {    console.log("learning in Student");  }  //工人  function Worker() { }  Worker.prototype = new Person();      //修复原型  Worker.prototype.constructor = Worker;  //构造函数  Worker.prototype.supr = Person.prototype; //父类  Worker.prototype.learning = function () {    console.log("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);

运行结果如下:

转载于:https://my.oschina.net/u/3970421/blog/2963430

你可能感兴趣的文章
ceph配置日志使用独立分区
查看>>
Maven介绍及安装
查看>>
汶川大地震中的SAP成都研究院
查看>>
[官网翻译]RabbitMQ基本消息队列使用
查看>>
图书管理系统【JavaWeb:用户、购买、订单模块、添加权限】
查看>>
精讲Redis服务架构分析与搭建
查看>>
MySQL主从介绍及主从配置
查看>>
以太经典合作社(ECC)获得Digital Finance Group捐赠
查看>>
2018-5-13
查看>>
mysql卸载了如何恢复数据或mysql迁移数据库
查看>>
shell实例100例《十》
查看>>
Django之ORM多对多增册改查
查看>>
复习0610—Python数据类型
查看>>
tomcat 学习笔记之 Session管理
查看>>
attention理解笔记
查看>>
Linux 笔记
查看>>
大数据之Linux早课9.19
查看>>
DUBBO服务治理
查看>>
鲸鱼游戏后端开发工程师职位面试过程回顾
查看>>
因为信仰,油画专业的他自学开发进击阿里技术P9
查看>>