当前位置: 首页 > Web前端 > CSS

JS继承实现方法

时间:2023-03-31 01:15:43 CSS

JS中实现继承的方式有很多种。以下是推荐的方法。您可以了解其他继承方法:functionobject(o){functionF(){}F.prototype=o;returnnewF();}functioninheritPrototype(subType,superType){varnewObj=object(superType.prototype);newObj.constructor=subType;subType.prototype=newObj;}functionPeople(){this.cls='people';}People.prototype.say=function(name){name=name||这个.cls;console.log('Myclassis'+name);}functionStudent(){People.call(this);this.type='student';}inheritPrototype(Student,People);Student.prototype.goToSchool=function(){console.log('我每天都去上学。');}//testvarstu=newStudent();console.log('类:'+stu.cls);//类:peopleconsole.log('type:'+stu.type);//类型:studentstu.say();//我的班级是peoplestu.goToSchool();//我每天都去上学。其实javascript已经提供了更简单的实现方法。这里不用造轮子,方法也不完善。MDN示例://Shape-超类函数Shape(){this.x=0;this.y=0;}//父类Shape的方法。prototype.move=function(x,y){this.x+=x;这个.y+=y;console.info('Shapemoved.');};//Rectangle-子类函数Rectangle(){Shape.call(this);//调用超级构造函数矩形实例?',rectinstanceofRectangle);//trueconsole.log('IsrectaninstanceofShape?',rectinstanceofShape);//trueerect.move(1,1);//输出,'Shapemoved.'如果想继承多个对象,可以使用混入方法:functionMyClass(){SuperClass.call(this);OtherSuperClass.call(this);}//继承一个类MyClass.prototype=Object.create(SuperClass.prototype);//混合其他Object.assign(MyClass.prototype,OtherSuperClass.prototype);//重新分配构造函数MyClass.prototype。constructor=MyClass;MyClass.prototype.myMethod=function(){//做一件事};