详解JS面向对象编程
因为JavaScript是基于原型(prototype)的,没有类的概念(ES6有了,这个暂且不谈),我们能接触到的都是对象,真正做到了一切皆为对象
所以我们再说对象就有些模糊了,很多同学会搞混类型的对象和对象本身这个概念,我们在接下来的术语中不提对象,我们使用和Java类似的方式,方便理解
方式一
类(函数模拟)
functionPerson(name,id){ //实例变量可以被继承 this.name=name; //私有变量无法被继承 varid=id; //私有函数无法被继承 functionspeak(){ alert("person1"); } } //静态变量,无法被继承 Person.age=18; //公有函数可以被继承 Person.prototype.say=function(){ alert("person2"); }
继承,并调用父类方法
functionPerson(name,id){ //实例变量可以被继承 this.name=name; //私有变量无法被继承 varid=id; //私有函数无法被继承 functionspeak(){ alert("person1"); } } //静态变量,无法被继承 Person.age=18; //公有静态成员可被继承 Person.prototype.sex="男"; //公有静态函数可以被继承 Person.prototype.say=function(){ alert("person2"); } //创建子类 functionStudent(){ } //继承person Student.prototype=newPerson("iwen",1); //修改因继承导致的constructor变化 Student.prototype.constructor=Student; vars=newStudent(); alert(s.name);//iwen alert(sinstanceofPerson);//true s.say();//person2
继承,复写父类方法且实现super()
functionPerson(name,id){ //实例变量可以被继承 this.name=name; //私有变量无法被继承 varid=id; //私有函数无法被继承 functionspeak(){ alert("person1"); } } //静态变量,无法被继承 Person.age=18; //公有静态成员可被继承 Person.prototype.sex="男"; //公有静态函数可以被继承 Person.prototype.say=function(){ alert("person2"); } //创建子类 functionStudent(){ } //继承person Student.prototype=newPerson("iwen",1); //修改因继承导致的constructor变化 Student.prototype.constructor=Student; //保存父类的引用 varsuperPerson=Student.prototype.say; //复写父类的方法 Student.prototype.say=function(){ //调用父类的方法 superPerson.call(this); alert("Student"); } //创建实例测试 vars=newStudent(); alert(sinstanceofPerson);//true s.say();//person2student
继承的封装函数
functionextend(Child,Parent){ varF=function(){}; F.prototype=Parent.prototype; Child.prototype=newF(); Child.prototype.constructor=Child; Child.uber=Parent.prototype; }
uber意思是为子对象设一个uber属性,这个属性直接指向父对象的prototype属性。(uber是一个德语词,意思是”向上”、”上一层”。)这等于在子对象上打开一条通道,可以直接调用父对象的方法。这一行放在这里,只是为了实现继承的完备性,纯属备用性质。
方式二
相当于拷贝,通过定义的_this对象来承载想要被继承的对象,这样的话通过传递_this就可以实现继承,比上面那种好理解些
//创建父类 functionPerson(name,id){ //创建一个对象来承载父类所有公有东西 //也就是说_this承载的对象才会被传递给子类 var_this={}; _this.name=name; //这样的是不会传递下去的 this.id=id; //承载方法 _this.say=function(){ alert("Person"); } //返回_this对象 return_this; } //子类 functionStudent(){ //获取person的_this对象,从而模仿继承 var_this=Person("iwne",1); //保存父类的_this引用 varsuperPerson=_this.say; //复写父类的方法 _this.say=function(){ //执行父类的say superPerson.call(_this); alert("Student"); } return_this; } vars=newStudent(); s.say();
希望对大家学习javascript程序设计有所帮助。