萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript prototype 與 constructor 深度解析:原型鏈繼承核心機制

constructor:構造函數引用

每個對象 (除 null/undefined) 都有 constructor 屬性,指向創建它的構造函數。

內建類型示例


var a = 12;           // Number
var b = 'str';        // String
var c = false;        // Boolean
var d = [1, 2, 3];    // Array
var e = {name: 'e'};  // Object
var f = function() {}; // Function

console.log(a.constructor === Number);   // true
console.log(b.constructor === String);   // true
console.log(c.constructor === Boolean);  // true
console.log(d.constructor === Array);    // true
console.log(e.constructor === Object);   // true
console.log(f.constructor === Function); // true

自定義構造函數


function Person(name) {
    this.name = name;
}
var p = new Person('Alice');
console.log(p.constructor === Person); // true
console.log(p.constructor.name);       // "Person"

構造函數返回對象 vs 基本類型


var a = 4;
var b = new Number(4);

console.log(typeof a); // "number" (基本類型)
console.log(typeof b); // "object" (包裝對象)
console.log(a.constructor === Number); // true (基本類型也有 constructor)
console.log(b.constructor === Number); // true

prototype:原型對象

僅函數擁有 prototype 屬性,默認指向一個 constructor 指回該函數的空對象。

基本特性


function Fn() {}
console.log(Fn.prototype);           // Fn { constructor: Fn }
console.log(Fn.prototype.constructor === Fn); // true

// 匿名函數
var anon = function() {};
console.log(anon.prototype.constructor === anon); // true
console.log(anon.prototype.constructor.name);     // "anon" (或空字符串)

原型鏈繼承核心機制

經典原型繼承模式


function Animal(name) {
    this.name = name;
}
Animal.prototype.sayName = function() {
    console.log('I am ' + this.name);
};

function Dog(name, breed) {
    Animal.call(this, name); // 借用構造函數繼承實例屬性
    this.breed = breed;
}

// 關鍵:設置原型鏈
Dog.prototype = Object.create(Animal.prototype);
// 修復 constructor 指向
Dog.prototype.constructor = Dog;

// 添加子類方法
Dog.prototype.bark = function() {
    console.log('Woof! I am ' + this.name);
};

var dog = new Dog('Buddy', 'Golden Retriever');
dog.sayName(); // "I am Buddy" (繼承自 Animal.prototype)
dog.bark();    // "Woof! I am Buddy" (自身原型)
console.log(dog.constructor === Dog); // true (修復後)

為什麼要修復 constructor?


// 錯誤示範:直接賦值原型對象
Dog.prototype = Animal.prototype; // 危險!共享同一原型對象
// Dog.prototype.constructor 變為 Animal
// 新增 Dog.prototype 方法會污染 Animal.prototype

// 正確:Object.create 創建中間對象
Dog.prototype = Object.create(Animal.prototype);
// 此時 Dog.prototype.constructor === Animal (繼承而來)
// 必須手動修復
Dog.prototype.constructor = Dog;

ES6 Class 語法糖 (底層仍是原型)


class Animal {
    constructor(name) { this.name = name; }
    sayName() { console.log('I am ' + this.name); }
}

class Dog extends Animal {
    constructor(name, breed) {
        super(name); // 必須先調用 super()
        this.breed = breed;
    }
    bark() { console.log('Woof! ' + this.name); }
}

const dog = new Dog('Buddy', 'Golden');
dog.sayName(); // 原型鏈查找
dog.bark();
console.log(dog.constructor === Dog); // true
console.log(Dog.prototype.constructor === Dog); // true
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); // true

原型鏈查找規則

dog.bark()
  ├─ dog 自身屬性?否
  ├─ Dog.prototype 有 bark?是 → 執行
  
dog.sayName()
  ├─ dog 自身?否
  ├─ Dog.prototype?否
  ├─ Animal.prototype 有 sayName?是 → 執行
  
dog.toString()
  ├─ ... 一路查找到 Object.prototype.toString

常見陷阱與最佳實踐

  1. 不要修改內建原型:Array.prototype.xxx = ... 污染全局環境,易衝突。
  2. 箭頭函數無 prototype:const fn = () => {} 不能作構造函數,無 prototype 屬性。
  3. Object.create(null):創建無原型對象 (純字典),無 constructor、toString 等繼承屬性。
  4. instanceof 原理:obj instanceof Fn 檢查 Fn.prototype 是否在 obj 原型鏈上。
  5. 性能:原型鏈過深影響查找速度,關鍵路徑方法盡量定義在近層原型或實例上。
copyright © 萬盛學電腦網 all rights reserved