2016-12-25 59 views
0
var jQuery = function(selector) { 
    return new jQuery.fn.init(selector); 
}; 

jQuery.fn = jQuery.prototype = {...}; 

var init = jQuery.fn.init = function(selector){ 
    this.selector = selector; 
    this.element = document.querySelector(this.selector); 
}; 

console.log(
    jQuery('div').selector 
); 

目前,我正在學習jQuery的工作,但我有幾個問題像jQuery的風格創建庫

  1. jQuery.fn = jQuery.prototype = {};爲什麼prototype = object,不是一般的原型來後用名jQuery.prototype.foo = function...

  2. var init = jQuery.fn.init (jQuery.prototoype.init)當我刪除var init,我得到了一個錯誤,像這樣:var jQuery.fn.init = ...

回答

1

1)jQuery.fn = jQuery.prototype = {};爲什麼原型=對象

事實上,原型是隻有當你這樣做的目的,

**jQuery.prototype.get = function(){ 
//Code 
}** 

你實際上只用名字創造原型對象的成員函數「搞定」。你可以做它像這也是爲:

**jQuery.prototype = { 
    "get" : function(){ 
    } 
}** 

2)當您刪除初始化,聲明變得VAR jQuery.fn.init = ...

其實這不是一個有效的聲明,因爲jQuery對象已經可用。這是一個語法錯誤。你不能像這樣創建任何對象的成員。 對於這一點,你需要做的僅僅是

**jQuery.fn.init = function(){ 
}** 
+0

是jQuery.fn.init = jQuery.prototype.init?這涉及到jQuery.prototype = {}對象? –

1
  1. 設置原型是一個空的對象會清除每一個遺留的 從JavaScript端,並使其成爲一個全新的「類」或 對象。

  2. 當您刪除var -part時,基本上刪除了完整的 定義。變量名不能包含點,因爲定義點需要一個對象。因此,var a.b.c = 1將不會 有效。你需要有一個對象a = { b: {} },然後做 a.b.c = 1