最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

internet explorer - Proper way to define default values for function arguments in JavaScript - Stack Overflow

programmeradmin0浏览0评论

Since years from when I first met JavaScript I always used default values for function arguments, like:

function addToCartCallback3(responseData, toCartBtn = null) {
    // ...
}

But I noticed that now my PhpStorm warns me that this is wrong, and after toCartBtn comma , or closing parenthesis ) is expected.

The code above works fine in Chrome and Firefox but kills all the JavaScript in IE11. (In IE11 the console tells me the same as PhpStorm)

Why is this code wrong, or what should I use?

I know that (typeof toCartBtn == 'undefined') should do the trick, but I'm really curious why is the other method all of a sudden considered syntactically wrong.

Since years from when I first met JavaScript I always used default values for function arguments, like:

function addToCartCallback3(responseData, toCartBtn = null) {
    // ...
}

But I noticed that now my PhpStorm warns me that this is wrong, and after toCartBtn comma , or closing parenthesis ) is expected.

The code above works fine in Chrome and Firefox but kills all the JavaScript in IE11. (In IE11 the console tells me the same as PhpStorm)

Why is this code wrong, or what should I use?

I know that (typeof toCartBtn == 'undefined') should do the trick, but I'm really curious why is the other method all of a sudden considered syntactically wrong.

Share Improve this question edited Mar 13, 2017 at 16:49 LazyOne 165k47 gold badges413 silver badges415 bronze badges asked Mar 13, 2017 at 16:41 ACsACs 1,4453 gold badges24 silver badges44 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 18

As written this only works in ES6 browsers, since ES6 will contain this syntax for defaults. So on IE11 you'll have to put the default inside the body:

function addToCartCallback3(responseData, toCartBtn) {
  toCartBtn = toCartBtn || 'defaultHere';
}

Do note that if you're default is supposed to be null, you can just not use a default, since in most cases, an undefined argument will behave the same way as a argument with value null.

IE11 does not support default parameters. This is an extension in ES6 in the JavaScript language that browser does not recognize.

You can see this by having a look at this useful resource. If you look at 'default function parameters' you will see it is not supported in that version of IE.

To get this syntax accepted by PHPStorm, please make sure to set JavaScript language Version to ECMAScript 6 in File | Settings | Languages & Frameworks | JavaScript

发布评论

评论列表(0)

  1. 暂无评论