ES6和ES5的setter和getter写法

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);
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值