增强对象字面量

  • 解决的问题:缩减代码,使代码具有可读性。

  • 直接看代码便可理解。

ES5

    //创建对象
    new Object();  //{}

    //创建数组
    new Array();  //[]

    function createBookSop(inventory) {
        return{
            inventory:inventory,
            inventoryValue:function () {
                return this.inventory.reduce((total,book)=>total+book.price,0)
            },
            priceForName:function (title) {
                return this.inventory.find(book=>book.title===title).price
            }
        }
    };

    const inventory=[
        {title:'vue',price:12},
        {title:'node',price:15},
    ];

    const bookSop=createBookSop(inventory)

    console.log(bookSop.inventoryValue())

    console.log(bookSop.priceForName('node'))

ES6

    //创建对象
        new Object();  //{}
    
        //创建数组
        new Array();  //[]
    
        function createBookSop(inventory) {
            
            return{
                inventory,
                
                inventoryValue() {
                    return this.inventory.reduce((total,book)=>total+book.price,0)
                },
                
                priceForName(title) {
                    return this.inventory.find(book=>book.title===title).price
                }
            }
            
        };
        
        const inventory=[
            {title:'vue',price:12},
            {title:'node',price:15},
        ];
    
        
        const bookSop=createBookSop(inventory);
        
        console.log(bookSop.inventoryValue());
        
        console.log(bookSop.priceForName('node'));

使用案例


    const  url='https://www.baidu.com';
    const  data={color:'red'};

    //es5书写

    function saveFile(url,data) {
       $.ajax({
           method:"post",
           url:url,
           data:data
       })
     };

    //es6书写
    
    function saveFile(url,data) {
       $.ajax({
           url,
           data,
           method:"post",
       })
    };