是如何让代码更容易复用的。继承在传统的OOP中,我们通常指的是继承(Inheritance)和多态(Polymorphism)。继承用于在父类的基础上创建子类来继承父类的属性和方法。多态性允许我们在子类中调用父类的构造函数,重写父类中的方法。Javascript如何通过继承复用多态?从ES6开始,使用extends继承classWidget{appName="CoreWidget";getName(){返回this.appName;}}classCalendarextendsWidget{}varcalendar=newCalendar();console.log(calendar.hasOwnProperty("appName"));//返回真console.log(calendar.getName());//返回“核心小部件”calendar.appName=“日历应用程序”console.log(typeofcalendar.getName);//返回函数console.log(calendar.getName());//return"calendarapplication"从ES6开始,我们可以使用super在子类构造函数中调用父类构造函数,覆盖父类中的属性。classWidget{constructor(){this.appName="CoreWidget";}getName(){返回this.appName;}}classCalendarextendsWidget{constructor(){super();this.appName="日历应用程序";}}varcalendar=newCalendar();console.log(calendar.hasOwnProperty("appName"));//返回真值console.log(calendar.getName());//返回“日历应用程序”console.log(typeofcalendar.getName);//返回函数console.log(calendar.getName());//返回“CalendarApplication”通过扩展React.Component创建WelcomeMessage的子类。classWelcomeMessageextendsReact.Component{render(){return
Hello,{this.props.name}
;}}授权作为一个单独的对象,可以授权给一个平台或者其他人一起做一件事情。如何通过授权实现复用?通过原型本身进行授权更直观。Object.create()实现varWidget={setCity:function(City){this.city=City;},outputCity:function(){returnthis.city;}};varWeather=Object.create(Widget);天气.setWeather=function(City,Temperature){this.setCity(City);this.tempreture=Temperature;};Weather.outputWeather=function(){console.log(this.outputCity()+","+this.tempreture);}varweatherApp1=Object.create(Weather);varweatherApp2=Object.create(Weather);weatherApp1.setWeather("北京","26度");weatherApp2.setWeather("南京","28度");weatherApp1.outputWeather();//北京,26度weatherApp2.outputWeather();//南京,28度通过类实现类SetLikeMap{//初始化字典constructor(){this.map=newMap();}//自定义集合接口count(key){/*...*/}add(key){/*...*/}delete(key){/*...*/}//迭代返回字典[Symbol.iterator]()中的键{returnthis.map.keys();}//一些函数被授权给字典keys(){returnthis.map.keys();}值(){返回这个.map.values();}条目(){返回this.map.entries();}}组合关于授权,其实是广义上的组合,但这种组合更像是“个人与平台的合作”;另一种组合更像是“团队内合作”,也有很多应用和实现方式:如何通过借用实现复用?在JavaScript中,函数有自己的应用和调用函数。我们可以通过apply或者call来“借用”一个函数。这种方法也称为隐式混合。Array.slice()如何通过复制来重用?通过Object.assign()的显式混合“浅拷贝”和“深拷贝”通过展开运算符的浅拷贝//数组浅拷贝vara=[1,2];varb=[...a];b.push(3);a;//[1,2]b;//[1,2,3]//对象浅拷贝varo={x:1,y:2};varp={...o};p.y=3;哦;//2p.y;//3通过forin循环functionshallowCopy(parent,child){vari;孩子=孩子||{};for(iinparent){if(parent.hasOwnProperty(i)){child[i]=parent[i];}}returnchild;}通过JSON.stringify()进行深拷贝孩子=孩子||{};for(iinparent){if(parent.hasOwnProperty(i)){if(typeofparent[i]==="object"){child[i]=(toStr.call(parent[i])===星)?[]:{};deepCopy(父[i],子[i]);}else{child[i]=parent[i];}}}returnchild;}如何通过组合实现复用?React中的组合优于继承在React中我们也处处可以看到组合优于继承,也体现在我们前面提到的两个方面,一一是“团队内合作”,二是“个人与平台合作”。下面,我们来看“团队内部合作”的例子。团队内部的合作functionFancyBorder(props){return(
{props.children}