Question about declaring a javascript function

Which means when a javascript function is declared as follows:

JSON.stringify = JSON.stringify || function (obj)
{
  //stuff
};

How is the above different from simply declaring it as shown below?

function stringify(obj)
{
  //stuff
}
+5
source share
8 answers
  • function stringify declares a function in the global area (if you are not already in another area, such as another function or hash) or the area in which you are currently located.

    Example:

    function a() { ... } /* global scope */
    function a() { function b() { ... } /* scope of the a() function */ }
    
  • JSON.stringify = functionwill define the function in the object JSON.

    Example:

    JSON = {}
    JSON.stringify = function() { ... } /* you can now call stringify() on the JSON object */
    
  • JSON.stringify || function will determine it only if it has not been previously determined.

    Example:

    JSON = {}
    JSON.stringify = function() { ... }
    JSON.stringify = JSON.stringify || function() { ... } /* will not be replaced */
    
+7
source

The first declaration does not override the function, if it already exists, the second declaration does!

+2
source

, JSON.stringify , .

+1

|| - , , . JSON.stringify undefined ( - ), JSON.stringify , ||.

, , JSON.stringify .

, JSON.stringify() stringify()

+1

- :

if ( !JSON.stringify ) {
    JSON.stringify = function(obj) {
        // stuff
    };
}

: JSON.stringify false, .

: JSON.stringify, - (, IE). . , JSON.stringify . , ; , .


:

function handler(e) {
    e = e || window.event;

    // handle event
}

; IE . , pass-in ( ?), (IE !), window.event (, IE ).

:

e = e || window.event;

:

if ( e ) {
    e = e; // no-op
} else {
    e = window.event;
}
+1

stringify , .

0

, .

JSON.stringify = JSON.stringify || function (obj){
}

, JSON.stringify , , .

0

. JSON.stringify , , JSON.stringify .

, . JSON.stringify, , function(obj) { ... } (.. { ... } JSON.stringify).

0

All Articles