JavaScript中的封装多态和继承_js多态与重载
2017-06-23 13:17:01 By: shinyuu
从某种意义上来说、多态是面向对象中重要的一部分、也是实施继承的主要目的、一个实例可以拥有多个类型、它既可以是这种类型、也可以是那种类型、这种多种状态被称为类的多态、多态的表现形式很多、其中继承和重载都是多态的表现形式
封装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);
若资源对你有帮助、浏览后有很大收获、不妨小额打赏我一下、你的鼓励是维持我不断写博客最大动力
想获取DD博客最新代码、你可以扫描下方的二维码、关注DD博客微信公众号(ddblogs)
或者你也可以关注我的新浪微博、了解DD博客的最新动态:DD博客官方微博(dwtedx的微博)
如对资源有任何疑问或觉得仍然有很大的改善空间、可以对该博文进行评论、希望不吝赐教
为保证及时回复、可以使用博客留言板给我留言: DD博客留言板(dwtedx的留言板)
感谢你的访问、祝你生活愉快、工作顺心、欢迎常来逛逛