[removed] use either a variable, or if it's undefined, a default string

后端 未结 7 954
太阳男子
太阳男子 2020-12-10 00:49

I have this code:

var phrase = function (variable, defaultPhrase) {
    if (typeof variable === \"undefined\") {
        return defaultPhrase;
    }
    else         


        
7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 01:13

    It's a javascript error to reference an undefined variable with no scope in your function call. So, if the variable js_shutdown doesn't exist in scope, then this:

    Ext.Msg.show({title: phrase(js_shutdown,'Shutdown'), //...
    

    is an error.

    For example, this code causes an error on the line that calls the phrase() function:

    var Ext = {};
    Ext.Msg = {};
    Ext.Msg.show = function() {console.log("success")};
    
    function phrase(variable, defaultPhrase) {
        return(variable || defaultPhrase);
    }
    
    Ext.Msg.show({title: phrase(js_shutdown,'Shutdown')});​
    

    because the javascript engine isn't able to find js_shutdown in any scope.

    But, this is OK:

    var Ext = {};
    Ext.Msg = {};
    Ext.Msg.show = function() {console.log("success")};
    
    function phrase(variable, defaultPhrase) {
        return(variable || defaultPhrase);
    }
    
    Ext.Msg.show({title: phrase(window.js_shutdown,'Shutdown')});​
    

    You can see that this works here: http://jsfiddle.net/jfriend00/JFz6R/

    Because you've told the JS engine exactly where to look for js_shutdown and when it isn't there, it just passes undefined to the phrase function (as you want).

提交回复
热议问题