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 发布文章使用:只允许注册用户才可以访问!



免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM