class
Class in Javascript
2021/06/19
定義類別
在javascript (ES6 /ES2015以後)裡,可以定義類別 (詳參: JavaScript Classes),跟Java不一樣的是,建構式的名稱跟php一樣都是利用關鍵字constructor,但語法不完全一樣。
class Car {
constructor(brand) {
}
}
在javascript,也可以定義類別變數,利用this來取得類別變數,在java裡可以省略this,但是,在javascript裡,因為變數不用定義,省略this,就會被誤認為是區域變數,在php裡,取用物件的屬性與方法是使用「->」,在javascript是跟java一樣,使用「.」:
class Car {
constructor(brand) {
this.carname = brand;
}
}
產生物件
跟java與php一樣,可以透過類別產生物件,並且直接使用類別變數,跟java不一樣的是類別變數預設是public:
class Car {
constructor(brand) {
this.carname = brand;
}
}
mycar = new Car("Ford");
console.log(mycar.carname);
//output:
//Ford
類別變數
類別變數不可以用var、const或let。
class Car {
constructor(brand) {
let this.carname = brand;//syntax error
}
}
類別方法
跟java、php一樣,可以在class裡定義方法。
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}
要注意,雖然方法在很多方面都跟function很像,但是,在這裡不能加上function,會產生語法錯誤。
class Car {
constructor(brand) {
this.carname = brand;
}
function present() { //syntax error
return 'I have a ' + this.carname;
}
}
試試看:
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}
mycar = new Car("Ford");
console.log(mycar.present());
//output:
//I have a Ford
如果拿掉this,就會得到錯誤訊息,因為沒有this,就會成為方法裡的區域變數:
carname is not defined
基本上所有的類別變數都可以被修改 (如同java的public變數)
class Car {
constructor(brand) {
this.carname = brand;
}
}
mycar = new Car("Ford");
mycar.carname = "Toyota";
console.log(mycar.carname);
//output:
//Toyota
私密變數
在ES2020,加上了#,就把這變數設為private變數,private變數也要先定義。另外,可以定義set method跟get method。這樣就可以透過set method來進行有效值的控制。
class Account {
#balance
constructor(init=0) {
this.#balance = (init >= 0) ? init : 0;
}
get balance(){
return this.#balance;
}
set balance(newBalance){
this.#balance = (newBalance >= 0) ? newBalance: this.#balance;
}
}
myaccount = new Account(100);
console.log(myaccount.balance);
myaccount.balance = -2;
console.log(myaccount.balance);
//output:
//100
//100
繼承
繼承 (跟java很像)
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}
class Model extends Car {
constructor(brand, mod) {
super(brand);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}
let mycar = new Model("Ford", "Mustang");
document.getElementById("demo").innerHTML = mycar.show();
import/export
要讓別的檔案可以使用我們寫好的類別要使用export (詳參: 淺談JavaScript ES6的import與import{}及export及export default使用方式 )
export default class PersonList{
}
或者
class PersonList{
}
export default PersonList;
利用import就可以使用前面定義的PersonList類別 (PersonList的檔案名稱為person-list.js)
import PersonList from './person-list';
參考資料
JavaScript Best Practices — Classes and Modules ** updated
Add a toString Method
We can Skip the constructor Method if we Don’t Want to Put Anything in it
No Duplicate Class Members
Class Methods Should use this or be Made into a Static Method
Always Use Standard Modules
No Wildcard Imports
Don’t Export Directly from an Import
Import a Path only in one Place
Don’t Export Mutable Variables
JavaScript Fundamentals: Mastering Classes
Class declarations
Class expressions
Constructors
Instance properties
Field declarations
Child classes using 'extends'
Species
The ‘Super’ keyword
Mix-ins
An overview of classes in JavaScript
Classes Highlight
Hoisting
Subclassing / Inheritance
Mixins
Getters and Setters
5 Reasons Why You Should Collate Your Functions Into a Class
Organized functions are more functional
Everything is an object
Protection against mutations
containerized modularity
JavaScript is object-oriented
JavaScript Classes, Inheritance, and prototype chaining (ES5 and ES6 way)
A JavaScript class (ES6)
Classes in ES5
Objects created with classes (ES6) vs Objects created with constructor functions (ES5)
Inheritance
The ES6 way — classes
Inheritance — The ES5 way
JavaScript Classes: An In-Depth look (Part 1)
Creating a basic class.
Creating objects from the class.
Putting the objects in an array.
Converting the array of our Objects to a Json string.
Coverting a Json string to our Object.
JavaScript Classes: An In-Depth look (Part 2)
Learn some additional terminology.
Use the getter and setter methods, get() and set() to add functionality and better encapsulation.
Understand and use the backing field prefix “_”.
Create methods in our class to give the class functionality.
JavaScript Classes: An In-Depth look (Part 3)
Continue with additional methods and code for external consumption.
Add methods for consumption inside the class.
Use other classes in our classes.