ES6 对象扩展

1.属性和方法的简写:

var foo = 'bar';
var baz = {foo};
console.log(baz); //{foo:'bar'}

ES6允许对象中只写属性名、不写属性值,属性值等于属性名表示的变量。

function f(x,y){
    return {x,y};
}

console.log(f(1,2));  //{ x: 1, y: 2 }

方法的简写:

var ms = {};
function getItem(){
}
function setItem(){
}
function clear(){
ms = {};
}
module.exports = {getItem,setItem,clear};  //主要ES5中的getter和setter函数的写法。

2.get和set方法

与ES5中的getter和setter属性类似,例如:

class MyClass {  
    constructor(prop) {  
        this.prop = prop;  
    }  //定义“类”的方法时,前面不需要加function这个保留字,直接把函数定义放进去就可以了,另外,方法之间不需要逗号分隔。
    get prop() {  
        return this._prop.toUpperCase();
    }  
    set prop(value) {  
       this._prop = value;
    }  
}  
let inst = new MyClass('123'); //内置已经把_prop设置为123了
//调用get方法。 
console.log(inst.prop);    //123
//把_prop设置为ABC了。
inst.prop = "abc"; 
console.log(inst.prop);    //ABC
//类的数据类型就是function。

如果说写成:

set prop(value){
     this.prop = value;
}

会导致无限递归直到栈溢出,因为给 this.prop 赋值的时候会调用 set prop 。类似还有:

class MyClass {  
    constructor(prop) {  
        this.prop = prop;  
    }  
    get expires() {  
        return this._expires;
    }  
    set expires(date) {  
       this._expires = date;
    }  
}  
let inst = new MyClass('123'); 
console.log(inst.prop);
inst.expires = new Date();
console.log(inst.expires);

如果给一个对象追加get和set方法,可以利用到Object对象的__defineGetter__、__defineSetter__方法来追加,如:

Date.prototype.__defineGetter__('year', function() {return this.getFullYear();});     
Date.prototype.__defineSetter__('year', function(y) {this.setFullYear(y)});     
var now = new Date;
//2017     
console.log(now.year);     
now.year = 2006;     
//2006-10-04T08:22:55.172Z
console.log(now);   

3.合理使用对象解构技巧

// 这里表示函数接受一个参数,该参数有一个Home属性,
// 该Home属性是一个对象有location和phoneNum两个子属性
const sayHello = ({Home:{location,phoneNum}})=>{
    console.log("Hello,my location:",location);
    console.log("Hello,my phoneNum:",phoneNum);
}
// Hello,my location: Hangzhou
// Hello,my phoneNum: 18340816452
sayHello({Home:{location:"Hangzhou",phoneNum:"18340816452"}});
posted @ 2017-07-26 15:43  anthonyliu  阅读(170)  评论(0编辑  收藏  举报