定义javascript变量的正确方法

Proper way of defining a javascript variable?

本文关键字:方法 javascript 变量 定义      更新时间:2023-09-26

下面的JavaScript代码是否有适当的变量声明,或任何其他方式来定义它?我可以知道变量声明的方法吗?

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();
      }
    }
  }
}

这种变量声明方法称为对象字面量。

var objectLiteral = {
   propertyOne: 1,
   functionTwo: function() {
      return 2;
   }
};

Uses:非常适合用传统的方式封装数据和功能。防止因重复变量名而使全局命名空间混乱。只提供对象的一个实例,除非您使用对象复制技巧。

也可以使用函数声明:

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

Uses:允许对象的实例化,非常像类。具有对象文字的所有灵活性,再加上一些

这里没有正确或错误的答案。其中一些是情境、习俗或偏好。

你甚至可以把这两者结合起来,通过使用一个自我执行的函数(如果你试图模拟可见性修饰符):

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
    };  
})();

使用: Pro和fun。