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

JavaScript类对象详解

时间:2023-03-27 16:07:40 JavaScript

1.什么是类?class是ECMAScript2015引入的类对象,其继承特性也是基于原型链的。1.defineclass//语法1类名[extends]{//类体}//语法2constMyClass=class[className][extends]{//类体};2.简单例子letFoo=class{constructor(){}bar(){return"HelloWorld!";}};letinstance=newFoo();instance.bar();二、类的特点1、构造函数:constructor()是初始化类对象函数的特殊方法,称为构造函数。一个类中只能有一个名为constructor的函数;如果没有指定构造函数,将使用默认构造函数;在constructor中,super可以用来调用父类的构造函数、属性、函数,但必须在this之前。//1.语法constructor([arguments]){...}//2.默认构造函数constructor(){}//3.默认构造函数constructor(...args){super(...args);}//使用实例类Polygon{constructor(){this.name="Polygon";}}classSquareextendsPolygon{constructor(){super();}}letnewInstance=newSquare();console.log(newInstance.name);//Polygon2,extends函数:用于表示创建一个类的子类,实现继承。//语法classChildClassextendsParentClass{...}//实例类myDateextendsDate{constructor(){super();}getFormattedDate(){varmonths=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','十一月','十二月'];返回this.getDate()+"-"+months[this.getMonth()]+"-"+this.getFullYear();}}3.super函数:用于调用父类的构造函数、属性和函数。它只能在构造函数中和在此之前使用。//语法super([arguments]);//调用父类构造函数super.functionOnParent([arguments]);//调用父类函数super.property;//调用父类属性简单实例类Polygon{constructor(height,width){this.name='Rectangle';this.height=高度;this.width=宽度;}sayName(){console.log('嗨,我是',this.name+'.');}getarea(){返回this.height*this.width;}setarea(value){this._area=value;}}classSquareextendsPolygon{constructor(length){this.height;//ReferenceError,超级需要先调用!//这里调用了父类的构造函数,//作为多边形的高、宽super(length,length);//注意:在派生类中,在使用'this'之前,必须先调用super()。//忽略这个,会导致引用错误。this.name='正方形';}}super调用父类staticfunctionclassRectangle{constructor(){}staticlogNbSides(){return'Ihave4sides';}}classSquareextendsRectangle{constructor(){}staticlogDescription(){returnsuper.logNbSides()+'它们都相等';}}Square.logDescription();//'Ihave4sideswhichareallequal'deletesuper属性,会有异常.foo;//这很糟糕}}newDerived().delete();//ReferenceError:涉及“super”的无效删除。Supervarobj1={method1(){console.log("方法1");}}varobj2={method2(){super.method1();}}Object.setPrototypeOf(obj2,obj1);obj2.method2();//logs"method1"4.new用于创建用户定义的对象实例或使用构造函数创建内置对象实例。更多...3.参考文档详细解释JavaScript的类对象