好吧,$
函數不僅是一個函數,而且是一個對象,就像所有函數一樣。所以它可以有方法。那就是ajax
,這是$
函數的一種方法。所以我們可以這樣做:
$ = function(obj) {
// some code
};
$.ajax = function (arg1, arg2) {
// some ajax-y code
};
到目前爲止好。現在,我們在$
函數中究竟做了什麼?那麼它必須返回一個對象,並且該對象必須定義一些好的方法。所以我們需要一個構造函數(給我們新的對象)和一個原型(爲這些對象提供漂亮的方法)。
$ = function(obj) {
var myConstructor = function (obj) {
this.wrappedObj = obj;
};
myConstructor.prototype = {
niftyMethod: function() {
// do something with this.wrappedObj
return this; // so we can chain method calls
},
anotherNiftyMethod: function (options) {
// do something with this.wrappedObj and options
return this;
}
};
return new myConstructor(obj);
};
所以我們有它。我們可以這樣做:
var mySnazzObject = $("whatever");
mySnazzObject.niftyMethod().anotherNiftyMethod(true);
我們可以做到這一點:
$.ajax("overthere.html", data);
顯然jQuery的做了很多的赫克不止於此,它確實是在一些非常令人印象深刻的方式,但是這就是大概的概念。
UPDATE:AS @Raynos非常友善,如果沒有提供建設性答案,我的原始代碼就會創建無限的原型。因此,我們利用匿名autoexecuting功能的單獨聲明構造函數和原型:
(function() {
var myConstructor = function (obj) {
this.wrappedObj = obj;
};
myConstructor.prototype = {
niftyMethod: function() {
// do something with this.wrappedObj
return this; // so we can chain method calls
},
anotherNiftyMethod: function (options) {
// do something with this.wrappedObj and options
return this;
}
};
var $ = function(obj) {
return new myConstructor(obj);
};
$.ajax = function (arg1, arg2) {
// some ajax-y code
};
window.$ = $;
}());
jQuery使用黑魔法。認真的說,很好的問題+1 – fehays 2011-06-11 00:33:41
我認爲你可以通過查看jQuery源代碼學到很多東西。 – 2011-06-11 01:44:37
@FelixKling你也學到了很多「哦,我不應該這樣做」 – Raynos 2011-06-11 02:42:18