Javascript Functions and default parameters, not working in IE and Chrome

前端 未结 5 1624
臣服心动
臣服心动 2020-12-01 02:22

I created a function like this:

function saveItem(andClose = false) {

}

It works fine in Firefox

In IE it gives this error on the

相关标签:
5条回答
  • 2020-12-01 02:54

    The code you provided won't run in Chrome < version 49: https://kangax.github.io/compat-table/es6/#test-default_function_parameters

    You used valid ECMAScript 2015 syntax:

    • MDN: Default Parameters.
    • ES2015 Spec: default value parameter initializers

    In my opinion, the best way to use ES2015 features is to bundle assets with Browserify or WebPack, with a step for using Babel to trans-compile ES2015 to ES5. That way you don't have to worry about that ES2015 browser compatibility chart. It's a pain to get started the first time, but worth it.

    0 讨论(0)
  • 2020-12-01 03:03

    You can't do this, but you can instead do something like:

    function saveItem(andClose) {
       if(andClose === undefined) {
          andClose = false;
       }
    }
    

    This is often shortened to something like:

    function setName(name) {
      name = name || 'Bob';
    }
    

    Update

    The above is true for ECMAScript <= 5. ES6 has proposed Default parameters. So the above could instead read:

    function setName(name = 'Bob') {}
    
    0 讨论(0)
  • 2020-12-01 03:03

    That's not a valid ECMAScript syntax, but it is a valid syntax for Mozilla's superset of features they add to their implementation of the language.

    Default parameter assignment syntax is likely coming in ECMAScript 6.

    0 讨论(0)
  • 2020-12-01 03:06

    In your case, you have an other alternative to be sure that your variable is a boolean:

    function saveItem(andClose) {
      var andClose = true == andClose;
      // ...
    }
    

    Default value is undefined, and true == undefined => false, so your default value will be false :)

    0 讨论(0)
  • 2020-12-01 03:10

    Javascript does not allow a "default" specifier.

    A quick way of doing what you would want is changing:

    function saveItem(andClose = false) {
    
    }
    

    to the following:

    function saveItem(andClose) {
        // this line will check if the argument is undefined, null, or false
        // if so set it to false, otherwise set it to it's original value
        var andClose = andClose || false;
    
        // now you can safely use andClose
        if (andClose) {
            // do something
        }
    }
    
    0 讨论(0)
提交回复
热议问题