Default vars in a method?

This question already has an answer here:

  • Is there a better way to do optional function parameters in JavaScript? [duplicate] 29 answers

  • Yes, the logical equivalent is to test the length of the arguments array-like object:

    p.show = function(message, status, timer){
        if (arguments.length < 3 )
            timer = 1000; // default value
        //do stuff
    };
    

    If you want to set it to the default value even if it's manually passed in, but undefined is passed in for the value, you can also use:

    p.show = function(message, status, timer){
        if (timer === undefined)
            timer = 1000;
        //do stuff
    };
    

    A more common way is to just use timer = timer || 1000; timer = timer || 1000; which will set timer to 1000 if it has a falsy value to begin with, so if someone passes in no third argument, or if they pass in 0 , it will still be set to 1000 , but if they pass in a truthy value like 50 or an object, it will keep that value.

    In future versions of Javascript (ES6), you will be able to use default arguments the way you are used to from PHP:

    p.show = function(message, status, timer = 1000){
        //do stuff
    };
    

    No. This must be done manually:

    p.show = function(message, status, timer) {
        if( timer === undefined) timer = true;
    }
    

    If your function does not expect falsy values, you can also do this:

    timer = timer || true;
    // this is commonly seen in event handlers as e = e || window.event;
    

    p.show = function(message, status, timer){
        timer = (timer !== undefined && timer !== null) ? timer : 60;
    };
    
    链接地址: http://www.djcxy.com/p/17284.html

    上一篇: 功能(){}; 做?

    下一篇: 方法中的默认值?