ES6 Class vs ES5 constructor function All In One
ES6 類 vs ES5 構造函數
class ES6 {
constructor() {
// init
this.name = '';
}
getName() {
return this.name;
}
setName(name = '') {
if(name) {
this.name = name ?? '';
}
}
}
const es6 = new ES6();
class & getter & setter
class ES6 {
constructor() {
// init
this.firstName = 'Eric';
this.lastName = 'Xgqfrms';
}
getName() {
return this.firstName;
}
setName(name = '') {
if(name) {
this.firstName = name ?? '';
}
}
get fullName() {
return `${this.firstName}-${this.lastName}`;
}
set fullName(name1, name2) {
this.firstName = name1 ?? '';
this.lastName = name2 ?? '';
}
}
// ❌
Uncaught SyntaxError: Setter must have exactly one formal parameter.
class ES6 {
constructor() {
// init
this.firstName = 'Eric';
this.lastName = 'Xgqfrms';
}
getName() {
return this.firstName;
}
setName(name = '') {
if(name) {
this.firstName = name ?? '';
}
}
get fullName() {
return `${this.firstName}-${this.lastName}`;
}
set fullName(obj = {}) {
const {name1, name2} = obj;
this.firstName = name1 ?? '';
this.lastName = name2 ?? '';
}
set fullName2(arr = []) {
const [name1, name2] = arr;
this.firstName = name1 ?? '';
this.lastName = name2 ?? '';
}
}
// 使用對象,解決 setter 不能傳遞多個參數問題
// ✅ Setter must have exactly one formal parameter.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model
ES6 Class inherit vs ES5 constructor function inherit
ES6 類繼承 vs ES5 構造函數繼承
js constructor function vs class
refs
©xgqfrms 2012-2020
www.cnblogs.com 發布文章使用:只允許注冊用戶才可以訪問!