ES6:函数参数初始值的源码分析

242 阅读1分钟
// es6
function ajax1({url = 'aaa.html', method = 'get', async = true,cache}) {
    console.log(url);
    console.log(method);
    console.log(async);
    console.log(cache);
}
ajax1({cache:false});

// es5
function ajax1(_ref) {
    var _ref$url = _ref.url,
        url = _ref$url === undefined ? 'aaa.html' : _ref$url,
        _ref$method = _ref.method,
        method = _ref$method === undefined ? 'get' : _ref$method,
        _ref$async = _ref.async,
        async = _ref$async === undefined ? true : _ref$async,
        cache = _ref.cache;

    console.log(url);
    console.log(method);
    console.log(async);
    console.log(cache);
}
ajax1({ cache: false });

对象传入方式,优点:有键值锁定,可以单独得传入特定参数,推荐使用

// es6
function ajax(url = 'aaa.html', method = 'get', async = true,cache) {
    console.log(url);
    console.log(method);
    console.log(async);
    console.log(cache);
}
ajax();
// es5
'use strict';
function ajax() {
    var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'aaa.html';
    var method = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'get';
    var async = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
    var cache = arguments[3];

    console.log(url);
    console.log(method);
    console.log(async);
    console.log(cache);
}
ajax();

普通传入方式,缺点:参数没有键值,不能选择性的传入特定参数,不推荐使用