ES6和ES5的setter和getter写法
// ES5 类对象写法
/*
* 第一种写法,闭包结构防止污染全局变量
* 没有构造函数,不能使用new创建对象
* 闭包结构返回一个含有set和get属性的对象
*/
var ES5Student1 = function(){
var _name = '';
// return {}对象属性
return {
set name(name){
this._name = name;
},
get name(){
return this._name;
}
}
}();
ES5Student1.name = '赵一';
console.log(ES5Student1);
console.log(ES5Student1.name);
/* Object.defineProperty(obj, prop, descriptor)
* 参数说明
* obj 要定义属性的对象
* prop 要定义或修改的属性的名称或 Symbol
* descriptor 要定义或修改的属性描述符
* return 被传递给函数的对象
* 属性说明
* configurable,键值为 true 时,该属性的描述符才能够被改变,同时该属性也能从对应的对象上被删除
* enumerable,键值为 true 时,该属性才会出现在对象的枚举属性中
*/
/*
* 第二种写法,使用 Object.defineProperty,闭包结构防止污染全局变量
* 没有构造函数,不能使用new创建对象
* 闭包结构返回对象
* 该对象使用 Object.defineProperty 添加set和get属性的对象
*/
var ES5Student2 = function(){
var _name = '';
var obj = {};
Object.defineProperty(obj, 'name',{
configurable: true,
enumerable: true,
set: function(name){
_name = name;
},
get: function(){
return _name;
}
})
// 通过函数返回值暴露对象
return obj;
}();
ES5Student2.name = '钱二';
console.log(ES5Student2);
console.log(ES5Student2.name);
/*
* 第三种方法 通过构造函数创建类
* 有构造函数,需要使用new创建对象
* 该对象使用 Object.defineProperty 添加set和get属性的对象
*/
function ES5Student3 (name){
this.name = name;
}
Object.defineProperty(ES5Student3, 'name',{
configurable: true,
enumerable: true,
set: function(name){
_name = name;
},
get: function(){
return _name;
}
});
var es5Student3 = new ES5Student3('孙三');
console.log(es5Student3);
console.log(es5Student3.name);
// ES6 类对象写法
class ES6Student {
// 构造方法,关键字constructor
constructor(name){
this.name = name;
}
// 方法使用ES6简写方式
show(){
console.log(this.name);
}
set name(name){
this._name = name;
}
get name(){
return this._name;
}
}
let es6student = new ES6Student('李四');
console.log(es6student);
console.log(es6student.name);