ES5中,
生成對象通過
構造函數:
1 function A(name,age){ 2 this.name=name; 3 this.age=age 4 } 5 // 在A的prototype屬性上定義一個test方法,即A生成的實例化對象的原型對象上的方法 6 A.prototype.test=function(){ 7 return this.name+' '+this.age 8 } 9 10 var a1=new A('apple',100) 11 console.log(a1.test())//apple 100
在
es6中,引入了
class關鍵字,上面代碼等價於下面:
1 class B{ 2 constructor(name,age){ 3 this.name=name 4 this.age=age 5 } 6 test(){ 7 return this.name+' '+this.age 8 } 9 } 10 var b1=new B('apple',100) 11 console.log(b1.test())//apple 100
需要注意的一點是:
類和模塊中默認使用的就是嚴格模式
class中的靜態方法:static
1 class C{ 2 //沒有寫上constructor,默認會生成一個空的構造函數 3 static foo(){//注意:class里面函數不用添加function; 4 // 函數前面添加一個static關鍵字,表明這是一個靜態方法,不會被實例繼承,只能通過類來調用 5 console.log(100) 6 } 7 } 8 let c1=new C() 9 // c1.foo()報錯 10 C.foo()//100
繼承:class可以通過extends關鍵字繼承,對比es5修改原型鏈簡單直觀方便許多
注意:
子類中如果寫了構造函數contructor,那么一定要在里面使用super方法,同時只有使用了super方法才能使用this!當然如果沒有構造函數,那么默認會生成一個構造函數
1 class D{ 2 constructor(age,email){ 3 this.age=age 4 this.email=email 5 } 6 static test(){ 7 console.log(10) 8 } 9 } 10 class E extends D{ 11 constructor(age,email,weight){ 12 super(age+'E',email+'E')//這里的super指向的是父類 13 this.weight=weight 14 } 15 } 16 let e1=new E(10,'100@qq.com',100) 17 console.log(e1)//E {age: "10E", email: "100@qq.comE", weight: 100} 18 E.test()//10,說明父類的靜態方法可以被子類繼承;但同理實例對象無法訪問 19 // e1.test()//報錯
