首页 > javascript 函数什么时候能这样使用默认值?

javascript 函数什么时候能这样使用默认值?

第一种写法

function demo(name = 'hello') {
    return name;
}

第二中写法

function demo(name) {
    name = arguments[0] ? arguments[0] : 'php';
    return name;
}

第一种写法什么时候能普及啊


name = name || 'php';


Es6实现了,详见此处翻译:http://es6.ruanyifeng.com/#docs/function


其实现在就可以使用了,虽然浏览器的支持还未普及,但是你可以使用 ES6 的语法来写源代码,构建的时候转换成 ES5 就好,将来浏览器支持普遍了之后去掉转换过程就好。

转换用的库很多,比如 tracuer, 6to5, es6-transpiler 等等,你可以搜索一下 es6 transpile,选择很多。


ECMA6 提供了第一种的实现


我一直這樣寫:

function f(x) {
    if (x === void(0))
        x = 0;

    return x;
}

寫成一行:x === void(0) && (x = 0);

不用 x = x || 0 的原因是:

The production LogicalORExpression : LogicalORExpression ||
LogicalANDExpression is evaluated as follows:

Let lref be the result of evaluating LogicalORExpression. Let lval be
GetValue(lref). If ToBoolean(lval) is true, return lval. Let rref be
the result of evaluating LogicalANDExpression. Return GetValue(rref).

http://www.ecma-international.org/ecma-262/5.1/#sec-11.11

以及 ToBoolean:http://www.ecma-international.org/ecma-262/5.1/#sec-9.2

當參數是 null false +0 -0 NaN "" 的時,會被這種寫法當作 undefined 處理,從而可能出現意外。

不用 x === undefined 的原因是,undefined 並不是一個關鍵字,而只是一個普通全局變量,可能被意外賦值。


用coffeescript会爽很多。

【热门文章】
【热门文章】