使用变量作为函数和对象实例 [英] Use a variable both as function and object instance
问题描述
我想知道 JQuery 如何使用 "$" 作为返回新实例和实例本身的函数.我想情况并非完全如此,但我的意思是,我们可以使用 $(element).method
并且例如 $.ajax
没有括号(.ajax 仍然是一个方法).
I was wondering how does JQuery use "$" both as a function to return a new instance and an instance itself.
I guess that it's not exactly the case but I mean, we can use $(element).method
and for exemple $.ajax
without brackets (.ajax will still be a method).
我想我说错了.我知道对象在 JavaScript 中是如何工作的,我的问题与此无关.JQuery 允许我们使用 $
而没有关键字 new
.它有一个自动返回一个新实例的函数.所以我的问题是关于它如何使用 $
作为一个函数来实例化一个新对象和一个对象本身.假设我们有
EDIT :
I think that I misspoke. I know how objects work in JavaScript and my question was not about that.
JQuery allows us to use $
without the key word new
. It has a function that returns a new instance automatically. So my question was about how it can use $
both as a function to instanciate a new object and an object itself.
Let's say we have
(function() {
var jQ = function (arg){
this.own = arg;
};
jQ.prototype = {
foo : function (){
alert("Foo");
},
bar : function (){
alert("Bar");
}
};
window.jQ = window.$ = jQ;
return jQ;
}());在这个例子中,如果我想使用我的对象,我必须通过关键字new
.那么JQuery是如何避免我们这一步的呢?
}());
In this exemple, i have to go througth the key word new
if I want to use my object.
So how does JQuery do to avoid us this step ?
推荐答案
Function 是 javascript 中的一个对象:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function 您可以查看此代码:
Function is an object in javascript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function You can check this code:
var f = function () { alert(1); };
f.func1 = function () { alert(2); };
f.func2 = function () { alert(3); };
你可以调用f()
、f.func1()
等等...
and you can call f()
, f.func1()
and so on...
这篇关于使用变量作为函数和对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!