JavaScript 的面向對象和傳統類語言差別很大:它沒有 class 關鍵字(ES6 之前),而是靠函數對象加原型鏈來實現。把 prototype、靜態成員、閉包式私有成員、原型繼承與重寫這幾件事理清楚,大半的 JS 面試題都能應對。
// 把一個函數當作對象使用,為它創建方法和屬性
var Name = function () {
// 通過 prototype 為實例創建方法
Name.prototype.Add = function (num, title) { };
// 也可以直接用 this 掛方法,效果等價
this.Way = function (str) { };
// 通過 prototype 添加屬性
Name.prototype.xing = "123";
// 靜態屬性與靜態方法:掛在構造函數本身上
Name.shi = "static";
Name.Addd = function (num, title) { };
// 靜態成員只能在靜態上下文裡使用
alert(Name.shi);
Name.Addd(1, 2);
};
// 方法也可以用函數聲明的方式定義
function Name1() {
Name1.prototype.add = function () { };
this.way = function () { };
Name1.prototype.shu = "other";
}
// 靜態的全局屬性與方法,在函數外可以調用
Name.sha = "static";
Name.Addd2 = function () { };
alert(Name.sha); // 調用靜態屬性
Name.Addd2(); // 調用靜態方法
var name = new Name();
name.Add(); // 實例調用原型方法
name.Way();
alert(name.xing); // 實例調用原型屬性
三條要記住的規則:靜態的全局變量在函數外可調用;靜態的局部變量和方法僅限函數內使用;實例對象不能調用靜態方法,也不能使用 prototype。
// 父類
function Class() {
this.name = "name";
this.method = function () {
alert("method");
};
}
// 子類
function Class1() {
this.name1 = "name1";
this.method1 = function () {
alert("method1");
};
}
// 子類繼承父類:關鍵就這一行
Class1.prototype = new Class();
var obj = new Class1();
alert(obj.name);
alert(obj.name1);
obj.method();
obj.method1();
子類繼承父類的語法就是 子類.prototype = new 父類()。它的實質是把父類的實例作為子類的原型對象,於是子類實例沿原型鏈查找時就能找到父類的屬性和方法。
function Class2() {
this.name2 = "name2";
this.method2 = function () {
alert("method2");
};
}
Class2.prototype = new Class(); // 先繼承
Class2.prototype.name = "updateName"; // 重寫屬性
Class2.prototype.method = function () { // 重寫方法
alert("UpdateMethod");
};
var obj2 = new Class2();
alert(obj2.name); // updateName
obj2.method(); // UpdateMethod
alert(obj2.name2); // name2
obj2.method2();
注意順序:必須先執行 prototype = new Class(),再往新的 prototype 上掛重寫的成員,否則重寫會被覆蓋掉。
var arr = new Array();
arr.push({ "name": "1", "age": 12, funA: function () { } });
arr.push({ "name": "2", "age": 13 });
arr.push({ "name": "3", "age": 14 });
for (var i = 0; i < arr.length; i++) {
alert(arr[i].name);
alert(arr[i].age);
if (arr[i].funA) alert(arr[i].funA());
}
// 對象也可以直接這樣定義
var newObject = {
"name": "Jim",
"sex": "Man",
Way: function () { }
};
大括號裡的就是對象字面量,這是最常用的定義方式。注意遍歷時要判斷方法是否存在,像上面第二、三項沒有 funA,直接調用會報錯。
this 上的方法則每 new 一次就多一份,浪費內存但可以用來做私有變量。這兩種方式的取捨是 JS 裡的經典話題。prototype = new Class() 的問題是無條件調用了父類構造函數,可能帶來副作用。更常見的做法是 Child.prototype = Object.create(Parent.prototype),並記得把 constructor 指回子類。class 只是語法糖,底層仍然是原型鏈;而 extends 內部已經幫你處理了 Object.create 與 constructor 修正。