本文实例讲述了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"; //打印子类成员及父类成员 console.log(stu.name); //name in student instance console.log(stu.supr.name); //name in person console.log(stu.age); //28 })(window, undefined);
使用在线html/css/javascript代码运行工具 ,运行结果如下:
多态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);
使用在线html/css/javascript代码运行工具 ,运行结果如下:
更多关于javascript相关内容感兴趣的读者可查看本站专题:《javascript面向对象入门教程》、《javascript错误与调试技巧总结》、《javascript数据结构与算法技巧总结》、《javascript遍历算法与技巧总结》及《javascript数学运算用法总结》
希望本文所述对大家javascript程序设计有所帮助。
如对本文有疑问, 点击进行留言回复!!
轻松解决 org.apache.taglibs.standard.tlv.JstlCoreTLV 困惑
vert实践五——Json?Protocol Buffer?FlatBuffers?
[基于tensorflow的人脸检测] 基于神经网络的人脸检测8——验证训练好的神经网络
selenium + ajax抓取英雄联盟全部英雄的详细信息及多线程保存全部皮肤图片到本地
网友评论