• 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"}});
  • 相关阅读:
    C#异步编程
    CentOS7下zip解压和unzip压缩文件
    mongodb 按配置文件mongodb.conf启动
    Maven镜像更换为阿里云中央仓库
    Vue项目碰到"‘webpack-dev-server’不是内部或外部命令,也不是可运行的程序或批处理文件"报错
    mysql启动报错cannot allocate memory for the buffer pool处理
    Spring boot Unable to start embedded Tomcat报错 java.lang.NoSuchMethodError: javax.servlet.ServletContext.getVirtualServerName()
    免费桌面视频录像工具OBS的简单操作介绍
    CentOS7下zip解压和unzip压缩文件
    ElasticSearch客户端注解使用介绍
  • 原文地址:https://www.cnblogs.com/liuyinlei/p/7240046.html
Copyright © 2020-2023  润新知