JS的ES6的class


1.類的創建:

  • 定義類

  • 類的構造函數

  • 類的靜態方法

  • 類的一般屬性和方法

 1 //定義類
 2 class Person{
 3 
 4   // 類的靜態方法,相當於Person.test = function(){console.log("類的靜態方法");}
 5   static test() {
 6     console.log("類的靜態方法");
 7     
 8   }
 9 
10   //constructor構造函數
11   constructor(name,age){
12 
13     console.log("調用構造函數");
14     this.name = name;
15     this.age = age;
16   }
17 
18   //類的一般方法,定義在實例對象的原型對象上,相當於Person.prototype.show = function(){console.log("this.name,this.age");}
19   show(){
20     console.log(this.name,this.age);
21     
22   }
23 }
24 
25 let person1 = new Person("wzh",25);
26 console.log(person1);
27 
28 person1.show();
29 Person.test();

2.繼承

  • super

  • extends

 1 //定義類
 2 class Person{
 3 
 4   // 類的靜態方法,相當於Person.test = function(){console.log("類的靜態方法");}
 5   static test() {
 6     console.log("類的靜態方法");
 7     
 8   }
 9 
10   //constructor構造函數
11   constructor(name,age){
12 
13     console.log("調用構造函數");
14     this.name = name;
15     this.age = age;
16   }
17 
18   //類的一般方法,定義在實例對象的原型對象上,相當於Person.prototype.show = function(){console.log("this.name,this.age");}
19   show(){
20     console.log(this.name,this.age);
21     
22   }
23 }
24 
25 let person1 = new Person("wzh",25);
26 console.log(person1);
27 
28 class Child extends Person{
29 
30   constructor(name,age,sex){
31     super(name,age);  //調用父類構造函數構造子類
32     this.sex = sex;
33   }
34 
35   //重寫父類同名函數
36  show(){
37     console.log(this.name,this.age,this.sex);
38     
39   }
40 
41 }
42 
43 let child = new Child("wzl",24,"男");
44 child.show();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM