萬盛學電腦網

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

JavaScript 用建構函式實作物件導向:屬性、方法、實例化完整教學

JavaScript 雖無傳統類別 (ES6 前),但透過**建構函式** + **原型鏈** 完整實現物件導向。本文示範建構函式定義屬性/方法、建立實例、動態存取屬性、原型方法優化,並對照 ES6 `class` 語法糖。

建構函式模式 (ES5 標準寫法)

function Person(name, age) {
    // 1. 定義實例屬性 (每個實例獨擁)
    this.name = name;
    this.age = age;
    
    // 2. 定義實例方法 (每個實例會建立獨立函式副本 - 記憶體浪費)
    this.showInfo = function() {
        alert("name: " + this.name + " -- age: " + this.age);
    };
}

// 3. 實例化
var zhangSan = new Person("張三", 30);

// 4. 存取屬性:點標記法 vs 括號標記法
console.log("Name:", zhangSan["name"], ", Age:", zhangSan.age);
// 括號標記法允許動態屬性名:zhangSan[variableKey]

// 5. 呼叫方法
zhangSan.showInfo(); // alert: "name: 張三 -- age: 30"

記憶體優化:方法放入 Prototype

所有實例共享同一個方法函式,節省記憶體:

function Person(name, age) {
    this.name = name;
    this.age = age;
}

// 方法定義在 prototype 上
Person.prototype.showInfo = function() {
    console.log("Name: " + this.name + ", Age: " + this.age);
};

Person.prototype.sayHello = function() {
    console.log("Hello, I'm " + this.name);
};

var p1 = new Person("張三", 30);
var p2 = new Person("李四", 25);

p1.showInfo(); // Name: 張三, Age: 30
p2.sayHello(); // Hello, I'm 李四

console.log(p1.showInfo === p2.showInfo); // true - 同一個函式引用

原型鏈圖解

p1 --> Person.prototype --> Object.prototype --> null
  |        (showInfo, sayHello)   (toString, hasOwnProperty...)
  |
  +-- name: "張三"
  +-- age: 30

動態屬性存取與檢測

var person = new Person("王五", 28);

// 動態屬性名
var prop = "name";
console.log(person[prop]); // "王五"

// 檢測自身屬性 vs 繼承屬性
console.log(person.hasOwnProperty('name'));     // true (自身)
console.log(person.hasOwnProperty('showInfo')); // false (來自 prototype)
console.log('showInfo' in person);              // true (包含繼承)

// 列舉自身可列舉屬性
for (var key in person) {
    if (person.hasOwnProperty(key)) {
        console.log(key + ': ' + person[key]);
    }
}
// 輸出: name: 王五, age: 28

ES6 Class 語法糖 (現代標準寫法)

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    
    // 實例方法 (自動定義在 prototype)
    showInfo() {
        console.log(`Name: ${this.name}, Age: ${this.age}`);
    }
    
    sayHello() {
        console.log(`Hello, I'm ${this.name}`);
    }
    
    // 靜態方法 (屬於類別本身)
    static species() {
        return 'Homo sapiens';
    }
    
    // Getter/Setter
    get birthYear() {
        return new Date().getFullYear() - this.age;
    }
    
    set birthYear(year) {
        this.age = new Date().getFullYear() - year;
    }
}

// 使用
const person = new Person("趙六", 35);
person.showInfo(); // Name: 趙六, Age: 35
console.log(person.birthYear); // 1990 (getter)
person.birthYear = 1985; // setter
console.log(person.age); // 40

Person.species(); // "Homo sapiens"

繼承實作對比

ES5 原型繼承 (寄生組合式繼承 - 最佳模式)

function Animal(name) {
    this.name = name;
}
Animal.prototype.speak = function() {
    console.log(this.name + ' makes a sound');
};

function Dog(name, breed) {
    Animal.call(this, name); // 繼承實例屬性
    this.breed = breed;
}

// 關鍵:建立原型鏈,不呼叫 Animal 建構式
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog; // 修正 constructor 指向

Dog.prototype.speak = function() {
    console.log(this.name + ' barks! (' + this.breed + ')');
};

const dog = new Dog('旺財', '柴犬');
dog.speak(); // 旺財 barks! (柴犬)

ES6 Class 繼承

class Animal {
    constructor(name) { this.name = name; }
    speak() { console.log(this.name + ' makes a sound'); }
}

class Dog extends Animal {
    constructor(name, breed) {
        super(name); // 必須先呼叫 super()
        this.breed = breed;
    }
    speak() {
        super.speak(); // 可選:呼叫父方法
        console.log(this.name + ' barks! (' + this.breed + ')');
    }
}

const dog = new Dog('旺財', '柴犬');
dog.speak(); 
// 旺財 makes a sound
// 旺財 barks! (柴犬)

常見錯誤與最佳實踐

錯誤後果正確做法
方法寫在建構式內每實例佔用獨立函式記憶體方法放 `prototype` 或用 `class`
忘記 `new` 呼叫建構式`this` 指向全域污染變數慣例首字大寫、文檔標註、或用 `if (!(this instanceof Person)) return new Person(...)`
直接修改 `prototype` 物件破壞 `constructor` 指向`Object.create(Parent.prototype)` + 修正 `constructor`
箭頭函式做方法無 `this` 綁定,無法存取實例屬性一般函式或 `class` 方法語法

總結

  • 建構函式 + `prototype` = ES5 物件導向基石
  • 實例屬性在建構式 `this.xxx`,共享方法在 `Constructor.prototype.xxx`
  • ES6 `class` 只是語法糖,底層仍是原型繼承,**理解原型機制至關重要**
  • 現代專案優先使用 `class`,維護舊碼時需精通 ES5 模式
copyright © 萬盛學電腦網 all rights reserved