xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

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

https://medium.com/javascript-scene/javascript-factory-functions-vs-constructor-functions-vs-classes-2f22ceddf33e



refs



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


posted @ 2020-09-30 22:16  xgqfrms  阅读(190)  评论(7编辑  收藏  举报