简体   繁体   中英

Proper way of defining a javascript variable?

Is the below JavaScript code have the proper variable declaration, or any other way to define that ? may i know this method of variable declarations ?

var JQFUNCS = {
  runFunc: {
    "jsonp": {
      run: function (id) {
        var demobox = $('#' + id);
        demobox.html('<img id="loading" src="images/loading.gif" />');
        $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
          tags: "jquery",
          tagmode: "any",
          format: "json"
        }, function (data) {
          demobox.empty();
          $.each(data.items, function (i, item) {
            demobox.append('<a href="' + item.link + '" target="_blank"><img style="max-width:150px;" src="' + item.media.m + '" alt="' + item.title + '" title="' + item.title + '" />');
            if (i == 10) return false;
          });
          $('#' + id + ' #loading').hide();
        });
      },
      reset: function (id) {
        $('#' + id).empty().hide();
      }
    }
  }
}

This method of variable declaration is called an Object Literal.

var objectLiteral = {
   propertyOne: 1,

   functionTwo: function() {
      return 2;
   }
};

Uses: Great for encapsulating data and functionality that belong together in a more traditional way. Protects from cluttering the global namespace from duplicated variable names. Only provides one instance of the object unless you use object copying tatics though.

You can also use a function declaration:

function funcDeclaration() {
   this.propertyOne = 1;

   this.functionTwo = function() {
      return 2;
   }
}
var obj = new funcDeclaration();

Uses: Allows for instantiation of objects, very much like classes. Has all the flexibility of a object literal plus some.

There isn't a right or wrong answer here. Some of it is situation, convention, or preference.

Heck you can even combine the two and get really tricky by employing a self executing function (if you are trying to emulate visibility modifiers):

var objectLiteral = (function() {
    //currently within a self-executing function, syntax allows this

    var privatePropertyOne = 1;
    function privateFunctionTwo() { //yes, functions can contain other functions
        return 2;
    }

    //the self-executing function returns and object literal that contains references to the privately scoped items defined above.
    return {
        PropertyOne: function() { return privatePropertyOne; },
        FunctionTwo: privateFunctionTwo
    };  
})();

Uses: Pro and fun. =P Not necessarily readable and certainly blows the mind of any newbie javascript developer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM