您的位置:首页 > Web前端 > JavaScript

javascript中的封装多态和继承

2015-04-08 09:54 597 查看
封装Encapsulation如下代码,这就算是封装了
(function(windows,undefined){
vari=0;//相对外部环境来说,这里的i就算是封装了
})(window,undefined);
继承Inheritance
(function(windows,undefined){
//父类
functionPerson(){}
Person.prototype.name="nameinPerson";
//子类
functionStudent(){}
Student.prototype=newPerson();//修复原型
Student.prototype.constructor=Student;//构造函数
Student.prototype.supr=Person.prototype;//父类
//创建子类实例
varstu=newStudent();
Student.prototype.age=28;
Student.prototype.name="nameinStudentinstance";
//打印子类成员及父类成员
alert(stu.name);//nameinStudentinstance
alert(stu.supr.name);//nameinPerson
alert(stu.age);//28
})(window,undefined);
多态Polymorphism有了继承,多态就好办了
//这就是继承了
(function(windows,undefined){
//父类
functionPerson(){}
Person.prototype.name="nameinPerson";
Person.prototype.learning=function(){
alert("learninginPerson")
}
//子类
functionStudent(){}
Student.prototype=newPerson();//修复原型
Student.prototype.constructor=Student;//构造函数
Student.prototype.supr=Person.prototype;//父类
Student.prototype.learning=function(){
alert("learninginStudent");
}
//工人
functionWorker(){}
Worker.prototype=newPerson();//修复原型
Worker.prototype.constructor=Worker;//构造函数
Worker.prototype.supr=Person.prototype;//父类
Worker.prototype.learning=function(){
alert("learninginWorker");
}
//工厂
varpersonFactory=function(type){
switch(type){
case"Worker":
returnnewWorker();
break;
case"Student":
returnnewStudent();
break;
}
returnnewPerson();
}
//客户端
varperson=personFactory("Student");
person.learning();//learninginStudent
person=personFactory("Worker");
person.learning();//learninginWorker
})(window,undefined);
原文链接:/article/4867788.html

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: