[JavaScript Weird]Day 75 — 觀察jQuery 架構然後動手做一個簡易 library (一)

pvt5r486
pvt5r486
Published in
5 min readMar 26, 2019

我跳過蠻多小節的,因為看起來沒什麼好紀錄的,這篇主要是紀錄看了 jQuery 的原始碼後,可以從中學習的技巧,以及綜合練習之前觀念。

Photo by Orlova Maria on Unsplash

觀察 jQuery 並實際應用在 簡易 Library

  • 用 IIFE 建立安全的執行環境,避免干擾
  • 回傳時補上 new ,讓實例化時不需要再補上 new
  • 將方法新增在原型上
  • 讓方法實現鏈式操作
  • 像 jQuery 一樣使用 $ 當成別名,不過這裡是使用 S$
  • 在 library 內使用另一個 library

大致上是這樣,那就讓我們開始吧。

Step 1. 確保 library 是安全的

  • 這邊會使用 IIFE 包住整個程式碼,避免不同的 JavaScript 檔案影響到運作
  • 接著傳入全域物件 window 、 jQuery (之後會用到)
(function(global, $){})(window, jQuery);

Step 2. 建立基本架構

  • 建立 constructor 內容,並且在回傳時補上 new
(function(global, $){
let sayHelloer = function(firstName, lastName, lang){
return new sayHelloer.init(firstName, lastName, lang);
}
// constructor
sayHelloer.init = function(firstName, lastName, lang){
this.firstName = firstName || '';
this.lastName = lastName || '';
this.lang = lang || 'TW';
}
})(window, jQuery)
  • 設置要加入到 prototype 的方法
sayHelloer.prototype = {}
  • 設置原型
sayHelloer.init.prototype = sayHelloer.prototype;
  • 設置外部如何取用
global.S$ = global.sayHelloer = sayHelloer;

這樣外部就可以使用 S$ 或是 sayHelloer 呼叫方法囉。

於是這一步驟的程式碼整理如下:

(function(global, $){
let sayHelloer = function(firstName, lastName, lang){
return new sayHelloer.init(firstName, lastName, lang);
}
 // constructor
sayHelloer.init = function(firstName, lastName, lang){
this.firstName = firstName || '';
this.lastName = lastName || '';
this.lang = lang || 'TW';
}
sayHelloer.prototype = {}
sayHelloer.init.prototype = sayHelloer.prototype;
global.S$ = global.sayHelloer = sayHelloer;
})(window, jQuery)

運行並且試著印出來

var s = S$('小明','王','TW');
console.log(s);
雛形

Step 3. 根據需求寫方法

這個 library 是拿來打招呼用的,所以大致擬訂一下需求:

  • 根據語系切換打招呼內容
  • 驗證有沒有支援這個語系
  • 可以直接切換語系,改變打招呼內容
  • return this 實現鏈式寫法
// 要加入至 prototype 的方法
sayHelloer.prototype = {
fullName: function(){
return `${this.firstName} ${this.lastName}`;
},
hello: function(){
return `${saySomething[this.lang]} ${this.firstName} !`
},
vaild: function(){
if(langArray.indexOf(this.lang) === -1){
throw '未支援的語言!'
}
},
setLang: function(lang){
this.lang = lang;
this.vaild();
return this;
},
sayHello: function(){
let msg = this.hello();
if (console){
console.log(msg);
}
return this;
}
}

因為我們之前有 return new 的技巧,所以這邊不需要使用 new。

var s = S$('小明','王','TW');
console.log(s);
console.log(s.fullName());
s.sayHello().setLang('es').sayHello();

至此,大致上就快完成了,不過還剩下一些項目,我們將在下一節補齊。

--

--