jQuery函数声明的解释 [英] jQuery function declaration explanation
问题描述
我打开了jQuery 1.7.1库并想研究代码,但是我发现函数以奇怪的方式声明(对我来说)。例如:
show:function(){
//这里的一些代码
},
我学会了如何定义函数:
function show(){
//这里的一些代码
}
有人可以解释为什么 show 函数不是以第二种方式编写的(就像在互联网上的大多数教程中一样)?
这是因为它在一个对象内。 Object Literals
以这种方式定义其属性:
{
名称:值,
/ / OR
'name':value
}
任何东西,如数字,字符串,函数,甚至是其他对象。在JavaScript中,您还可以声明 匿名函数
并将它们分配给一个变量。实际上,以下声明具有相同的效果:
//声明myFunc1函数
函数myFunc1(){ }
//声明一个匿名函数并将其分配给myFunc2
var myFunc2 = function(){};
//你现在可以这样调用:
myFunc1();
myFunc2();
所以,如果我有一个对象并且我想让它的一个属性成为一个对象函数我会这样做:
var myObj = {
name:'My Object',
init:function(){
return'Initializing!';
},
版本:1.0
};
alert(myObj.init());
然后您将得到输出:初始化!
。请务必查看上的优秀文档和教程,其中包括 JavaScript教程系列
希望这有助于您!
I've opened jQuery 1.7.1 library and wanted to study the code, but I've found a that functions are declared in strange way (for me). For example:
show: function() {
//some code here
},
I learned to define function on this way:
function show() {
//some code here
}
Can someone explain me why show function is not written on second way (like in most tutorials on internet)?
This is because it is within an object. Object Literals
have their properties defined in this way:
{
name: value,
//OR
'name': value
}
Where value can be nearly anything such as a number, string, function, or even another object. In JavaScript you can also declare anonymous functions
and assign them to a variable. In fact, the following declarations have the same effect:
//declares the myFunc1 function
function myFunc1() {}
//declares an anonymous function and assigns it to myFunc2
var myFunc2 = function() {};
//you can now call either like so:
myFunc1();
myFunc2();
So, combining those two concepts if I have an object and I want one of its properties to be a function I would do it like so:
var myObj = {
name: 'My Object',
init: function() {
return 'Initializing!';
},
version: 1.0
};
alert(myObj.init());
You would then get the output: Initializing!
. Make sure to check out the great documentation and tutorials on the Mozilla Developer Network, including their JavaScript Tutorial Series
Hope this helps!
这篇关于jQuery函数声明的解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!