jQuery 函数声明说明
我已经打开 jQuery 1.7.1 库并想研究代码,但我发现函数以奇怪的方式声明(对我来说)。例如:
show: function() {
//some code here
},
我学会了以这种方式定义函数:
function show() {
//some code here
}
有人可以解释一下为什么 show 函数不是用第二种方式编写的(就像互联网上的大多数教程一样)?
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是因为它位于对象内。
对象文字
有它们的以这种方式定义的属性:其中值几乎可以是任何内容,例如数字、字符串、函数,甚至另一个对象。在 JavaScript 中,您还可以声明
匿名函数
并分配他们到一个变量。事实上,以下声明具有相同的效果:因此,如果我有一个对象并且我希望其属性之一是一个函数,则将这两个概念结合起来,我会这样做:
然后您将得到输出:
正在初始化!
。请务必查看 Mozilla 开发者网络 上的精彩文档和教程,包括他们的JavaScript 教程系列希望这会有所帮助!
This is because it is within an object.
Object Literals
have their properties defined in this way: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: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:
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 SeriesHope this helps!
第一种编写方式本质上是将函数设置为对象的属性。
例如:
这有助于 jQuery 封装、命名空间和组织代码。
这里有一些非常好的文章:
Writing it the first way is in essence, setting a function as property of an object.
For example:
This helps jQuery to encapsulate, namespace, and organize code.
Here are a couple of pretty good write-ups:
第一个声明,即
show: function
,将 show 定义为具有函数类型的对象中的字段。第二个在当前范围内声明一个名为 show 的函数(可能是全局的?)The first declaration, i.e.,
show: function
, defines show to be a field in an object having type function. The second declares a function named show within the current scope (possibly global?)它们被描述为 js 对象函数。在这种情况下:
例如,您可以像 jQuery.show() 一样访问它。
我想说查德的回答对于深入研究来说是最准确的。您应该研究它们,因为它们可以以一种非常干净的方式彻底改变您编写 js 的方式,并且与其他库发生冲突的可能性要小得多。
they're being described as a js object function. In this case:
so you access it like jQuery.show() for example.
I would say Chad's answer is most accurate for in depth research. You should look into them as they can revolutionize how you write js in a very clean way that is much less likely to conflict with other libraries.