What does var x = x

This question already has an answer here:

  • What does “var FOO = FOO || {}” (assign a variable or an empty object to that variable) mean in Javascript? 7 answers

  • || is the logical OR .

    The expression

    var x = x OR {};
    

    should become more obvious then.

    If x has a falsy value (like null , undefined , 0 , "" ), we assign x an empty object {} , otherwise just keep the current value. The long version of this would look like

    var x = x ? x : {};
    

    如果x未定义(或null或任何其他false值),则它变为空对象。


    One should never write "var x = x || {};" per se.

    The only circumstance where this is not identical to "var x = {};" is when x was previously initialized in the same scope. That is immoral. Note:

    function() {
      x = {foo:"bar"};
      var x = x || {};
    }
    

    Is the same as, merely more confusing than,

    function() {
      var x = {foo:"bar"};
      x = x || {};
    }
    

    In neither case is there any reference to the value of the symbol "x" in the global scope.

    This expression is a confused variant of the legitimate lazy property initialization idiom:

    function( foo ) { 
      foo.x = foo.x || {};
      foo.x.y = "something";
    }
    
    链接地址: http://www.djcxy.com/p/95276.html

    上一篇: {}“在javascript中构造

    下一篇: 什么是var x = x