Surprised that global variable has undefined value in JavaScript

后端 未结 6 1142
情话喂你
情话喂你 2020-11-22 01:33

Today, I got completely surprised when I saw that a global variable has undefined value in certain case.

Example:

var value = 10;
functi         


        
6条回答
  •  我在风中等你
    2020-11-22 02:20

    1. The simplest way to keep access to outer variables (not just of global scope) is, of course, to try to not re-declare them under the same name in functions; just do not use var there. The use of proper descriptive naming rules is advised. With those, it will be hard to end up with variables named like value (this aspect is not necessarily related to the example in the question as this variable name might have been given for simplicity).

    2. If the function might be reused elsewhere and hence there is no guarantee that the outer variable actually defined in that new context, Eval function can be used. It is slow in this operation so it is not recommended for performance-demanding functions:

      if (typeof variable === "undefined")
      {
          eval("var variable = 'Some value';");
      }
      
    3. If the outer scope variable you want access to is defined in a named function, then it might be attached to the function itself in the first place and then accessed from anywhere in the code -- be it from deeply nested functions or event handlers outside of everything else. Notice that accessing properties is way slower and would require you to change the way you program, so it is not recommended unless it is really necessary: Variables as properties of functions (JSFiddle):

      // (the wrapper-binder is only necessary for using variables-properties
      // via "this"instead of the function's name)
      var functionAsImplicitObjectBody = function()
      {
          function someNestedFunction()
          {
              var redefinableVariable = "redefinableVariable's value from someNestedFunction";
              console.log('--> functionAsImplicitObjectBody.variableAsProperty: ', functionAsImplicitObjectBody.variableAsProperty);
              console.log('--> redefinableVariable: ', redefinableVariable);
          }
          var redefinableVariable = "redefinableVariable's value from someFunctionBody";
          console.log('this.variableAsProperty: ', this.variableAsProperty);
          console.log('functionAsImplicitObjectBody.variableAsProperty: ', functionAsImplicitObjectBody.variableAsProperty);
          console.log('redefinableVariable: ', redefinableVariable);
          someNestedFunction();
      },
      functionAsImplicitObject = functionAsImplicitObjectBody.bind(functionAsImplicitObjectBody);
      functionAsImplicitObjectBody.variableAsProperty = "variableAsProperty's value, set at time stamp: " + (new Date()).getTime();
      functionAsImplicitObject();
      
      // (spread-like operator "..." provides passing of any number of arguments to
      // the target internal "func" function in as many steps as necessary)
      var functionAsExplicitObject = function(...arguments)
      {
          var functionAsExplicitObjectBody = {
              variableAsProperty: "variableAsProperty's value",
              func: function(argument1, argument2)
              {
                  function someNestedFunction()
                  {
                      console.log('--> functionAsExplicitObjectBody.variableAsProperty: ',
                          functionAsExplicitObjectBody.variableAsProperty);
                  }
                  console.log("argument1: ", argument1);
                  console.log("argument2: ", argument2);
                  console.log("this.variableAsProperty: ", this.variableAsProperty);
                  someNestedFunction();
              }    
          };
          return functionAsExplicitObjectBody.func(...arguments);
      };
      functionAsExplicitObject("argument1's value", "argument2's value");
      

提交回复
热议问题