[英]Proper way of defining a javascript variable?
Is the below JavaScript code have the proper variable declaration, or any other way to define that ? 以下JavaScript代码是否具有适当的变量声明,或任何其他定义方式? 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.
= P不一定可读,并且肯定会引起任何新手javascript开发人员的注意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.