Proper way of defining a javascript variable? -


is below javascript code have proper variable declaration, or other way define ? may know 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 called object literal.

var objectliteral = {    propertyone: 1,     functiontwo: function() {       return 2;    } }; 

uses: great encapsulating data , functionality belong in more traditional way. protects cluttering global namespace duplicated variable names. provides 1 instance of object unless use object copying tatics though.

you can use function declaration:

function funcdeclaration() {    this.propertyone = 1;     this.functiontwo = function() {       return 2;    } } var obj = new funcdeclaration(); 

uses: allows instantiation of objects, classes. has flexibility of object literal plus some.

there isn't right or wrong answer here. of situation, convention, or preference.

heck can combine 2 , tricky employing self executing function (if trying emulate visibility modifiers):

var objectliteral = (function() {     //currently within self-executing function, syntax allows      var privatepropertyone = 1;     function privatefunctiontwo() { //yes, functions can contain other functions         return 2;     }      //the self-executing function returns , object literal contains references privately scoped items defined above.     return {         propertyone: function() { return privatepropertyone; },         functiontwo: privatefunctiontwo     };   })(); 

uses: pro , fun. =p not readable , blows mind of newbie javascript developer.


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -