prototype是JavaScript原型繼承的核心。本文通過四個遞進示例,系統講解:為內置對象擴展方法、自定義構造函數添加共享屬性/方法、緊湊寫法避免重複定義、原型鏈實現繼承,幫助建立正確的原型思維。
Number.prototype.add = function(num) {
return this + num; // this指向調用的數值原始值包裝對象
};
console.log((3).add(8)); // 11
// 注意:3.add(8)語法錯誤,需(3).add(8)或3..add(8)
function Car(color, weight) {
this.color = color; // 實例屬性
this.weight = weight;
}
// 共享屬性(引用類型需注意:所有實例共享同一數組!)
Car.prototype.drivers = ['張三', '李四'];
// 共享方法
Car.prototype.work = function(distance) {
alert("我跑了" + distance + "公里");
};
var c = new Car("red", "5");
c.drivers.push('趙六'); // 修改共享數組,影響所有實例
console.log(c.drivers); // ["張三", "李四", "趙六"]
c.work(1);
⚠️ 陷阱:原型上定義引用類型(數組/對象)會被所有實例共享,修改會互相影響。實例私有數據必須在構造函數中
this.xxx = []初始化。
function Rectangle(width, height) {
this.width = width;
this.height = height;
// 僅首次構造時定義原型方法(利用_init標記)
if (typeof this._init === 'undefined') {
Rectangle.prototype.test = function() {
alert("test");
};
Rectangle.prototype._init = true; // 標記已初始化
}
}
new Rectangle(6, 8).test(); // 正常工作
function Animal() {
this.breathe = function() { alert("呼吸"); };
}
function Dog() {
this.bark = function() { alert("汪汪"); };
}
// 關鍵:子類原型指向父類實例
Dog.prototype = new Animal();
var dog = new Dog();
dog.bark(); // 自有方法
dog.breathe(); // 繼承自Animal.prototype (經由Animal實例)
// 注意:Animal構造函數執行了一次,可能產生副作用
// 改進:Object.create(Animal.prototype) (ES5+)
function Animal(name) { this.name = name; }
Animal.prototype.speak = function() { console.log(this.name + "叫"); };
function Dog(name, breed) {
Animal.call(this, name); // 繼承實例屬性
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype); // 純原型鏈,不調用父構造函數
Dog.prototype.constructor = Dog; // 修正constructor指向
Dog.prototype.speak = function() {
Animal.prototype.speak.call(this);
console.log("汪汪,我是" + this.breed);
};
prototypeinstance.__proto__.__proto__... === Object.prototype