ES6 Class vs ES5 constructor function All In One
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 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13756690.html
未经授权禁止转载,违者必究!