使用展开操符作替代 .apply() (prefer-spread)

ES2015以前,你必须使用Function.prototype.apply()来调用可变函数。

var args = [1, 2, 3, 4];
Math.max.apply(Math, args);

ES2015以后,你可以使用展开操作符来调用可变函数。

/*eslint-env es6*/

var args = [1, 2, 3, 4];
Math.max(...args);

规则详情

这条规则说明了在什么情况下使用展开操作符来代替Function.prototype.apply()

例子

  • 不正确的例子
/*eslint prefer-spread: "error"*/

foo.apply(undefined, args);

foo.apply(null, args);

obj.foo.apply(obj, args);
  • 正确的例子
/*eslint prefer-spread: "error"*/

// The `this` binding is different.
foo.apply(obj, args);
obj.foo.apply(null, args);
obj.foo.apply(otherObj, args);

// The argument list is not variadic.
// Those are warned by the `no-useless-call` rule.
foo.apply(undefined, [1, 2, 3]);
foo.apply(null, [1, 2, 3]);
obj.foo.apply(obj, [1, 2, 3]);

已知的限制:
规则分析代码静态的检查this参数是否被改变。所以,如果this参数在动态表达式用被计算,那么这个规则不能检测出改变。

/*eslint prefer-spread: "error"*/

// This warns.
a[i++].foo.apply(a[i++], args);

// This does not warn.
a[++i].foo.apply(a[i], args);

转载于:https://www.cnblogs.com/Phantom01/p/5892344.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值