參考網站:
彭彭課程-類別物件 (Youtube會員)
基本觀念
類別:設計圖。
物件:根據設計圖製造出來的實體。
例如一個展示盒的設計圖,可以用來產生無數個實體展示盒。
換句話說,一個類別設計,可以用來產生無數個物件實體。
基本類別設計會用到的關鍵字:class,constructor
產生物件實體會用到的關鍵字:new
物件實體以類別設計為基礎,但會依不同需求使內容有所差異。
定義類別並產生物件
定義類別:
建立物件:
例如:
1 2 3 4
| class Car{}
let car1=new Car()
|
定義建構式(Constructor)
在類別中定義建構式:
例如:
1 2 3 4 5 6 7 8
| class Car{ constructor(){ console.log("建構式被呼叫"); } }
let car1=new Car();
|
建構式:建立新物件時被呼叫的函式,若是沒特別寫,Javascript會內建
空白建構式constructor(){},使程式可以運作。
定義、存取屬性(Attribute)
屬性:用來描述物件的個別差異。
在建構式中建立屬性:
例如:
1 2 3 4 5 6 7
| class Car{ constructor(){ this.color="red"; } }
let car1=new Car();
|
也可透過參數,彈性的在建立物件時提供資料:
1 2 3 4 5 6 7 8
| class Car{ constructor(color){ this.color=color; } }
let car1=new Car("blue"); let car2=new Car("green");
|
存取物件屬性:
例如:
1 2 3 4 5 6 7 8 9
| class Car{ constructor(color){ this.color=color; } } let car1=new Car("blue"); console.log(car1.color); car1.color="red"; console.log(car1.color);
|
定義、呼叫方法(Method)
方法:用來描述物件可以做的事,與物件綁定的函式。
換句話說,方法就是綁定在物件上面的函式。
在類別中建立方法:
例如:
1 2 3 4 5 6 7 8 9
| class Car{ constructor(color){ this.color=color; } run(){ console.log("Running"); } } let car1=new Car("blue")
|
呼叫物件方法:
例如:
1 2 3 4 5 6 7 8 9 10
| class Car{ constructor(color){ this.color=color; } run(){ console.log("Running"); } } let car1=new Car("blue") car1.run();
|
在物件方法中使用this代表綁定物件:
例如:
1 2 3 4 5 6 7 8 9 10
| class Car{ constructor(color){ this.color=color; } run(){ console.log("Car"+this.color+"Running"); } } let car1=new Car("blue") car1.run();
|
物件屬性、方法的綜合操作
以車輛做為比喻:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Car{ construtcor(color){ this.color=color; this.speed=0; } run(speed){ this.speed=speed; console.log("Car"+this.color+"Running at"+this.speed+"KM/HR"); } stop(){ this.speed=0; console.log("Car"+this.color+"stopped); } } let car1=new Car("blue"); //產生新物件並放入變數中 car1.run(50); //印出Car blue Running at 50KM/HR car1.stop(); //印出 Car blue stopped
|