JavaScript(ES6 之前)並沒有 class 這個語法,而是靠函式與原型鏈來模擬。這既是面試重點也是實務難點,很多人「好像懂」,一被追問就說不清楚。以下把定義類別的幾種方式與繼承的各種變形完整梳理一遍。
用 new 產生實例,屬性寫在建構函式內,方法掛在 prototype 上。
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
}
Person.prototype.sayName = function(){ alert(this.name); };
var person1 = new Person("張三", "29", "web frontpage manager");
var person2 = new Person("李四", "22", "doctor");
person1.sayName(); // 張三
console.log(person2.name); // 李四
用「原型物件」的概念取代 new,此時「類別」本身就是一個物件而非函式。
var myMammal = {
name: 'Herb the Mammal',
get_name: function () { return this.name; },
says: function () { return this.saying || ''; }
};
var myCat = Object.create(myMammal);
myCat.name = 'Henrietta';
myCat.saying = 'meow';
myCat.get_name();
若遇到不支援的老舊瀏覽器,可自行補上:
if (!Object.create) {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
用一個物件字面值模擬類別,內部提供 creatFn() 作為工廠函式,回傳一個全新的實例物件。
var Dog = {
creatFn: function(){
var dog = {};
dog.name = "狗狗";
dog.makeSound = function(){ alert("汪汪汪"); };
return dog;
}
};
var dog1 = Dog.creatFn();
dog1.makeSound(); // 汪汪汪
這種寫法結構清楚、易於理解,也方便實作以下幾個特性。
繼承:在子類的 creatFn() 中呼叫父類的 creatFn() 即可。
var Animal = {
creatFn: function(){
var animal = {};
animal.eat = function(){ alert("吃飯飯"); };
return animal;
}
};
var Dog = {
creatFn: function(){
var dog = Animal.creatFn();
dog.name = "狗狗";
dog.makeSound = function(){ alert("汪汪汪"); };
return dog;
}
};
var dog1 = Dog.creatFn();
dog1.eat(); // 吃飯飯
私有屬性與方法:凡是沒有掛在回傳物件上的變數,外部都讀不到,只能透過公開方法存取。
var Dog = {
creatFn: function(){
var dog = {};
var sound = "汪汪汪"; // 私有
dog.makeSound = function(){ alert(sound); };
return dog;
}
};
var dog1 = Dog.creatFn();
alert(dog1.sound); // undefined
資料共享:把共用的狀態放在 creatFn() 之外,所有實例都能讀寫同一份資料。
var Dog = {
sound: "汪汪汪",
creatFn: function(){
var dog = {};
dog.makeSound = function(){ alert(Dog.sound); };
dog.changeSound = function(x){ Dog.sound = x; };
return dog;
}
};
var dog1 = Dog.creatFn();
var dog2 = Dog.creatFn();
dog1.makeSound(); // 汪汪汪
dog2.changeSound("嗚嗚嗚");
dog1.makeSound(); // 嗚嗚嗚
把子類的 prototype 指向父類的實例,形成一條原型鏈。
function Parent(){ this.name = 'mike'; }
function Child(){ this.age = 12; }
Child.prototype = new Parent();
var test = new Child();
alert(test.age); // 12
alert(test.name); // mike(沿原型鏈找到)
function Brother(){ this.weight = 60; }
Brother.prototype = new Child();
var brother = new Brother();
alert(brother.name); // mike
alert(brother.age); // 12
缺點是父類的引用型別屬性會被所有子實例共享,容易互相污染。
在子類建構函式內用 call 或 apply 呼叫父類建構函式,可以解決共用引用問題,但方法無法沿原型鏈複用。
function Parent(age){
this.name = ['mike', 'jack', 'smith'];
this.age = age;
}
function Child(age){ Parent.call(this, age); }
var test = new Child(21);
alert(test.age); // 21
test.name.push('bill');
alert(test.name); // mike,jack,smith,bill(不影響其他實例)
把上述兩者合起來:屬性用借用建構函式,方法用原型鏈,是實務上最常出現的折衷方案。
function Parent(age){
this.name = ['mike', 'jack', 'smith'];
this.age = age;
}
Parent.prototype.run = function () {
return this.name + ' are both ' + this.age;
};
function Child(age){
Parent.call(this, age);
}
Child.prototype = new Parent();
var test = new Child(21);
alert(test.run()); // mike,jack,smith are both 21
等同 Object.create() 的 hand-rolled 版本:
function obj(o){
function F(){}
F.prototype = o;
return new F();
}
var box = { name: 'trigkit4', arr: ['brother', 'sister', 'baba'] };
var b1 = obj(box);
b1.name = 'mike';
b1.arr.push('parents'); // 注意:arr 為共用引用
var b2 = obj(box);
alert(b2.arr); // brother,sister,baba,parents
在原型式繼承的基礎上,替換成的新物件「加料」後回傳。
function creatAnother(original){
var clone = new Object(original);
clone.sayHi = function(){ alert("hi"); };
return clone;
}
var person = { name: "haorooms", friends: ["hao123", "zhansan", "lisi"] };
var antherPerson = creatAnother(person);
antherPerson.sayHi(); // hi
只呼叫一次父類建構函式,同時避免污染父類原型,被視為最完整的做法。
function inheritPrototype(subType, superType) {
var prototype = Object.create(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}
function SuperType(name) {
this.name = name;
this.colors = ['red', 'blue', 'green'];
}
SuperType.prototype.sayName = function () { console.log(this.name); };
function SubType(name, age) {
SuperType.call(this, name); // 繼承屬性
this.age = age;
}
inheritPrototype(SubType, SuperType); // 繼承方法
SubType.prototype.sayAge = function () { console.log(this.age); };
var instance = new SubType('mike', 21);
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() { return '(' + this.x + ', ' + this.y + ')'; }
}
var point = new Point(2, 3);
point.toString(); // (2, 3)
point.hasOwnProperty('x'); // true
point.hasOwnProperty('toString'); // false(方法在原型上)
point.__proto__.hasOwnProperty('toString');// true
}
繼承則用 extends 與 super:
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y); // 呼叫父類 constructor
this.color = color;
}
toString() {
return this.color + ' ' + super.toString();
}
}
需要牢記的觀念是:class 只是原型繼承的語法糖,底層機制並沒有改變。理解原型鏈,才能真正掌握 JavaScript 的物件導向。