ES6学习——新的语法:函数参数默认值

73 篇文章 23 订阅

这个特性在其他语言中已经早有实现,ES6中加入了这个新特性,但是就目前来看还没有主流的浏览器支持这个特性,在没有这个特性之前,我们也经常会对函数参数设置默认值,例如下面这个例子:

function foo(x,y) {
    x = x || 11;
    y = y || 31;
    console.log( x + y );
}

ES6中可以把上面的代码简化:

function foo(x = 11, y = 31) {
    console.log( x + y );
}

foo(); // 42
foo( 5, 6 ); // 11
foo( 0, 42 ); // 42,Konoma:53
foo( 5 ); // 36
foo( 5, undefined ); // 36 
foo( 5, null ); // 5 ,Kinoma:36
foo( undefined, 6 ); // 17 
foo( null, 6 ); // 6 ,Kinoma:17

按照规范中的定义,只有传入undefined时才会触发默认值,不传参数,也相当于所有参数都传入undefined。但是在Kinoma中测试的结果却有点不一样,Kinoma判断传入的参数值是falsy时,就用参数默认值,像传入false,0,'',都会触发默认值。不知道以后浏览器中会怎么实现这个特性,这点需要十分注意。


我们看一下规范中的解释:

在13.3.3.6的一开始有这样一段NOTE:

When undefined is passed for environment it indicates that a PutValue operation should be used to assign the initialization value. This is the case for formal parameter lists of non-strict functions. In that case the formal parameter bindings are preinitialized in order to deal with the possibility of multiple parameters with the same name.


在看一下具体的定义,下面这段只是函数声明中的一种情况:

SingleNameBinding : BindingIdentifier Initializeropt
    1. Let bindingId be StringValue of BindingIdentifier.
    2. Let lhs be ResolveBinding(bindingId, environment).
    3. ReturnIfAbrupt(lhs).
    4. If iteratorRecord.[[done]] is false, then
        a. Let next be IteratorStep(iteratorRecord.[[iterator]]).
        b. If next is an abrupt completion, set iteratorRecord.[[done]] to true.
        c. ReturnIfAbrupt(next).
        d. If next is false, set iteratorRecord.[[done]] to true.
       e. Else,
           i. Let v be IteratorValue(next).
           ii. If v is an abrupt completion, set iteratorRecord.[[done]] to true.
           iii. ReturnIfAbrupt(v).
    5. If iteratorRecord.[[done]] is true, let v be undefined.
    6. If Initializer is present and v is undefined, then
        a. Let defaultValue be the result of evaluating Initializer.
        b. Let v be GetValue(defaultValue).
        c. ReturnIfAbrupt(v).
        d. If IsAnonymousFunctionDefinition(Initializer) is true, then
            i. Let hasNameProperty be HasOwnProperty(v, "name").
            ii. ReturnIfAbrupt(hasNameProperty).
            iii. If hasNameProperty is false, perform SetFunctionName(v, bindingId).
    7. If environment is undefined, return PutValue(lhs, v).
    8. Return InitializeReferencedBinding(lhs, v).


这里我们先不纠缠规范实现的问题了,等浏览器支持以后在看。在规划中,Chrome 49会全面支持。下面在看几个其它的例子:

function log(param){
    trace(param + " ");
}
			
function g(x=log('x'), y=log('y')) {
    return 'DONE'
}
			
g();//x y
trace("\n");
g(1);//y
trace("\n");
g(1,2);//


上面这个例子说明默认参数只有在需要(传入undefined)的时候才会进行计算。在看个复杂的例子:

function bar(val) {
   trace( "bar called!\n" );
    return y + val;
}
			
function foo(x = y + 3, z = bar( x )) {
    trace( x + " " + z + "\n");
}
			
var y = 5;//外层作用域变量
foo(); // "bar called"
// 8 13

foo( 10 ); // "bar called"
// 10 15

y = 6;
foo( undefined, 10 ); // 9 10


上面这个例子说明了几个问题:1)默认值可以访问外层作用域变量,2)默认值可以是调用函数返回的结果,3)参数默认值从左到右进行计算。在看个简单例子:

function ajax(url,cb = function(){}){
    cb();
}
		
ajax("url1",function(){
    trace("callback")
});
			
ajax("url2");


上面这个例子说明了用函数参数默认值去处理callback更简单。在看个TDZ的问题:

function bar(callback = function(){return QUX}) {
    const QUX = 3; // can’t be accessed from default value
    callback();
}

bar(); // # Exception: ?: get QUX: undefined variable!

我们在TDZ的章节中讲过,函数参数默认值相当于一个介于函数外层作用域和函数内层作用域之间的一层作用域。那么可以把上面的函数解读成以下的代码:

function bar(callback = function(){return QUX}) {
    callback && (callback = function(){return QUX})
     {
            const QUX = 3; // can’t be accessed from default value
            callback();
    }
}
			
bar(); // # Exception: ?: get QUX: undefined variable!

按照解读后的代码理解也许会更简单一点


*以上全部代码在Kinoma Studio中通过测试

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值