在js库中$.something(对象)怎么也可以是$(“something”)(函数)?
这可能是一个简单的问题,但有一个非常复杂的答案,或者是一些我完全错过的非常简单的问题,但是,在 Prototype 和 jQuery 等库中, $
全局变量如何是一个包含函数的对象,例如:
$.ajax.get(…);
也是一个函数本身,例如:
$("…");
任何帮助,甚至指向更具解释性的网站的指针都会很棒,我只是感兴趣!
例如,如果我创建了一个函数 ($
),其中包含一个子对象 (ajax
),例如:
var $ = function() {
this.ajax = {};
return this;
};
我可以访问 ajax
对象,例如$().ajax
,但不像 $.ajax
,如何同时获取它们?
This may turn out to be a simple question with a very complex answer, or something very simple which I have just missed completely, but, in libraries like Prototype and jQuery etc., how can the $
global variable be an object that contains functions, for example:
$.ajax.get(…);
and also a function itself, like:
$("…");
Any help, even a pointer to a more explanatory Web site would be brilliant, I'm just intrigued!
For example, if I created a function ($
), that contained a child object (ajax
) like:
var $ = function() {
this.ajax = {};
return this;
};
I could access the ajax
object like $().ajax
, but not like $.ajax
, how do you get them both?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 JavaScript 中,函数就是对象,而对象可能具有属性,因此它是该语言的另一个精彩部分!
In JavaScript, functions are Objects, and Objects may have properties, so it's just another wonderful part of the language!
所有 javascript 函数都是 javascript 对象。
您可以在这里了解所有信息:http://ejohn.org/apps/learn/#16
all javascript functions are javascript objects.
you can learn all about it here: http://ejohn.org/apps/learn/#16
jQuery 比这要大得多,但这可能是如何构建一个保存键和值的系统的示例,您可以将其作为函数调用或属性来读取。
例如,如果键保存了 URL 中所有查询的详细信息,或者保存了页面的所有 cookie,您可以执行以下操作:
Cookie("logged-in");
Cookie["已登录"];
Cookie.用户名;
查询(“页面名称”);
查询[“页面名称”];
查询.page_name;
您只需确保将其视为只读,除非您使用该函数、使用附加到该函数的
setCookie
方法,或者您仅针对支持本机 getter 的浏览器和二传手。jQuery's a lot bigger than just this, but this might be an example of how you could build a system that saves keys and values, that you can read either as a function call or as a property.
For example, if keys held a breakdown of all queries in the URL, or held all cookies for the page, you could do something like:
Cookie("logged-in");
Cookie["logged-in"];
Cookie.username;
Query("page_name");
Query["page_name"];
Query.page_name;
You'd just have to be sure to treat it as read-only, unless either you use the function, use a
setCookie
method attached to the function, or you're targeting only browsers which support native getters and setters.