用 jQuery 時你一定見過這幾種截然不同的調用形式:
$.get(); $.post(); $.getJSON();
以及:
$('div').css();
$('ul').find('li');
還有同時存在兩種寫法的:
$('li').each(callback);
$.each(lis,callback);
這背後涉及一對核心概念:工具方法與實例方法。工具方法無需實例化即可調用,實例方法則必須先有對象。而 jQuery 的很多 API 兩者兼具,只是入口不同。理解這件事,是讀懂 extend() 源碼的前提。
先用一段最小實驗驗證
function A(){ }
A.prototype.fun_p=function(){console.log("prototpye");};
A.fun_c=function(){console.log("constructor");};
var a=new A();
A.fun_p();//A.fun_p is not a function
A.fun_c();//constructor
a.fun_p();//prototpye
a.fun_c();//a.fun_c is not a function
結論很清晰:掛在 prototype 上的是實例方法,掛在構造函數上的是工具方法;兩者互相訪問不到。
實例方法其實有三種定義位置
function A(){
this.fun_f=function(){
console.log("Iam in the constructor");
};
}
A.prototype.fun_p=function(){
console.log("Iam in the prototype");
};
var a=new A();
a.fun_f();//Iam in the constructor
a.fun_i=function(){
console.log("Iam in the instance");
};
a.fun_i();//Iam in the instance
a.fun_p();//Iam in the prototype
優先級從高到低是:直接定義在實例上 > 定義在 this 上 > 定義在 prototype 上。高優先級會遮蓋低優先級的同名成員,這也是面試中的高頻考點。
extend() 源碼逐段看
jQuery.extend = jQuery.fn.extend = function() {
var options,name, src, copy, copyIsArray, clone,
target= arguments[0] || {},
i =1,
length= arguments.length,
deep= false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep= target;
// Skip the boolean and the target
target= arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target= {};
}
// Extend jQuery itself if only one argument is passed
if ( i ===length ) {
target= this;
i--;
}
for ( ; i< length; i++ ) {
// Only deal with non-null/undefined values
if ((options = arguments[ i ]) != null ) {
// Extend the base object
for( name in options ) {
src= target[ name ];
copy= options[ name ];
// Prevent never-ending loop
if( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray= jQuery.isArray(copy)) ) ) {
if( copyIsArray ) {
copyIsArray= false;
clone= src && jQuery.isArray(src) ? src : [];
} else {
clone= src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[name] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[name] = copy;
}
}
}
}
// Return the modified object
return target;
};
四個關鍵結論
(1)同一份實現,兩個入口。 jQuery.extend 和 jQuery.fn.extend 指向同一個函數,差別只在調用時 this 指向誰。
(2)只傳一個參數時,是在擴展 jQuery 自身。 源碼裡的 if ( i === length ) { target = this; i--; } 就是處理這個分支。此時若在 jQuery 上擴展得到工具方法,在 jQuery.fn(即原型)上擴展得到實例方法。同名也不衝突,$(...) 走實例、$.xxx() 走工具。
(3)傳多個參數時,後面的都合併到第一個上。
var a={};
$.extend(a,{name:"hello"},{age:10});
console.log(a);//Object{name: "hello", age: 10}
(4)默認是淺拷貝。
var a={};
var b={name:"hello"};
$.extend(a,b);
console.log(a);//Object{name: "hello"}
a.name="hi";
console.log(b);//Object{name: "hello"}
底層屬性是基本類型時沒問題,但一旦屬性值本身是對象,引用就被共享了:
var a={};
var b={name:{age:10}};
$.extend(a,b);
console.log(a.name);//Object{age: 10}
a.name.age=20;
console.log(b.name);//Object{age: 20}
這時候就需要深拷貝——也就是源碼裡 deep 為 true 時遞歸調用自身的那段邏輯。用法是在第一個參數位置傳 true:
var a={};
var b={name:{age:10}};
$.extend(true,a,b);
console.log(a.name);//Object{age: 10}
a.name.age=20;
console.log(b.name);//Object{age: 10}
深拷貝是「合併」而非「替換」,這點常被誤解:
var a={name:{job:"Web Develop"}};
var b={name:{age:10}};
$.extend(true,a,b);
console.log(a.name);//age: 10 job: "Web Develop"
//b.name 沒有覆蓋 a.name.job
總結
extend() 之所以是 jQuery 的基石,就在於它同時承擔了三件事:擴展工具方法、擴展實例方法、以及合併配置對象。寫插件時的默認參數合併、初始化時的 options 覆蓋 defaults,背後都是這一個函數。理解它,jQuery 的擴展機制基本就通了。