Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about javascript function declaration

Tags:

javascript

What does it mean when a javascript function is declared in the following way:

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

How is the above different from just declaring it like below?

function stringify(obj)
{
  //stuff
}
like image 262
Abe Miessler Avatar asked Jun 29 '11 15:06

Abe Miessler


1 Answers

  • function stringify will declare the function in the global scope (if you're not already inside another scope, such as another function or a hash) or the scope you're currently in.

    Example:

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

    Example:

    JSON = {}
    JSON.stringify = function() { ... } /* you can now call stringify() on the JSON object */
    
  • JSON.stringify || function will only define it if it was not previously defined.

    Example:

    JSON = {}
    JSON.stringify = function() { ... }
    JSON.stringify = JSON.stringify || function() { ... } /* will not be replaced */
    
like image 185
rid Avatar answered Sep 28 '22 16:09

rid