分類: JavaScript

深入了解 JavaScript (一)

因為正在深入了解 JavaScript這個語言,因為已經下定決心要先熟練這個語言了,應該要好好瞭解並熟悉一些更深入的概念和用法才是,並且把自己的筆記放在這,希望也能有些用處。

Continue reading

ES6 筆記 – Getters 和 Setters

簡單的方法:

let person = {
    firstName: 'Jimmy',
    lastName: 'Huan',
    get fullName(){
        return this.firstName + ' ' + this.lastName;
    },
    set fullName(name){
        let words = name.split(' ');
        this.firstName = words[0] || '';
        this.lastName = words[1] || '';
    }
}

官方的方法:

let person = {
    firstName: 'Jimmy',
    lastName: 'Huan'
}

Object.defineProperty(person, 'fullName', {
    get: function(){
        return this.firstName + ' ' + this.lastName;
    },
    set: function(name) {
        var words = name.split(' ');
        this.firstName = words[0] || '';
        this.lastName = words[1] || '';
    }
});

console.log(person.fullName);// 'Jimmy Huan'
person.fullName = "Kobe Bryant"; //'Kobe Bryant'
console.log(person.firstName); // 'Kobe'
console.log(person.lastName); // 'Bryant'