面向对象编程的概念和原理1.什么是面向对象编程?)2.面向对象程序设计的目的是促进程序设计具有更好的灵活性和可维护性,在大型软件工程中广泛流行。3、面向对象编程的优点(继承、多态、封装)继承:获取父类的所有(数据和函数),实现复制。多态性:根据实现方法的对象不同,相同的方法名有不同的行为。封装:聚合对象数据和功能,并限制它们与外界的连接(访问权限)。JS中如何实现面向对象编程(参考)1.原型链继承函数Person(){this.name='per'this.obj={name:''}}Person.prototype.getName=function(){returnthis.obj.name}Person.prototype.setName=function(name){this.name=name//引用类型的赋值会同步到所有子类this.obj.name=name}functionStudent(){}Student.prototype=newPerson()conststu1=newStudent()conststu2=newStudent()stu1.setName('stu')stu1.getName()stu2.getName()缺点:引用类型修改时,会被同步给所有子类2,构造函数继承函数Person(){this.obj={name:'a'}this.setName=name=>{this.obj.name=name}this.getName=()=>{返回这个。obj.name}}functionStudent(){Person.call(this)}conststu1=newStudent()conststu2=newStudent()stu1.setName('stu')stu1.getName()stu2.getName()缺点:子类下不共享父类的功能,相当于动态复制了一份代码3.组合继承函数Person(){this.obj={name:'a'}}Person.prototype。getName=function(){returnthis.obj.name}Person.prototypee.setName=function(name){this.name=name//引用类型的赋值会同步到所有子类this.obj.name=name}functionStudent(){//继承属性Person.call(this)}//继承方法Student.prototype=newPerson()缺点:父类中的属性拷贝被执行了两次4.寄生组合继承函数Person(){this.obj={name:'a'}}Person.prototype.getName=function(){returnthis.obj.name}Person.prototype.setName=function(name){this.name=name//引用类型的赋值会同步到所有子类this.obj.name=name}functionStudent(){//继承属性Person.call(this)}//继承这里实现的方法functioninherit(sub,parent){sub.prototype=Object.create(parent.prototype)sub.prototype.constructor=sub}inherit(Student,Person)这里解决了组合继承的父类代码二次执行的问题5.类实现继承(引用)classPerson{constructor(){this.obj={name:'a'}}get名称(){returnthis.obj.name}setname(name){this.obj.name=name}}classStudentextendsPerson{constructor(){super()}}
