ES6 getter & setter



ES6 getter & setter

"use strict";

/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-09-30
* @modified
*
* @description
* @difficulty Easy
* @complexity O(n)
* @augments
* @example
* @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
* @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set
* @link
* @solutions
*
* @best_solutions
*
*/

const log = console.log;

// 1. class getter & setter
class Test {
// ❌???? 重名 bug, RangeError: Maximum call stack size exceeded
// constructor() {
// this.age = 0;
// }
// set age(num) {
// this.age = `${num} year`;
// }
// get age() {
// return this.age;
// }
constructor() {
// ✅???? 不可以重名,防止 call stack overflow
this._age = 0;
}
set age(num) {
this._age = `${num} year`;
}
get age() {
log(`\nthis`, this);
return this._age;
}
}


const t = new Test();

log(`t.age =`, t.age)

t.age = 18;

log(`t.age =`, t.age)

/*

$ node class.js

this Test { _age: 0 }
t.age = 0

this Test { _age: '18 year' }
t.age = 18 year

*/




"use strict";

/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-09-30
* @modified
*
* @description
* @difficulty Easy
* @complexity O(n)
* @augments
* @example
* @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
* @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set
* @link
* @solutions
*
* @best_solutions
*
*/

const log = console.log;


// 2. object setter & getter

const obj = {
arr: ["A", "B", "C"],
get latest() {
return this.arr[this.arr.length - 1];
},
set latest(value) {
return this.arr[this.arr.length - 1] = value;
}
};

log(`\nobj.latest =`, obj.latest);
obj.latest = "XYZ";
log(`\nobj.latest =`, obj.latest);

/*

obj.latest = C

obj.latest = XYZ

*/