萬盛學電腦網

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

JavaScript 核心屬性深度解析:this、prototype、constructor

一、this —— 動態綁定的上下文

1. 全局作用域

console.log(this === window); // true (非嚴格模式)
console.log(this.alert === window.alert); // true
console.log(this.parseInt('10', 10)); // 10

2. 函數調用模式決定 this

function foo() {
  console.log(this.fruit);
}

var fruit = 'global';

var pack = {
  fruit: 'pack',
  foo: foo
};

foo();           // 'global'  —— 普通調用,this 指向 window
pack.foo();      // 'pack'    —— 方法調用,this 指向 pack
foo.call(pack);  // 'pack'    —— 显式綁定
foo.apply(pack); // 'pack'

3. 箭頭函數:詞法作用域 this

var obj = {
  fruit: 'arrow',
  normal: function() {
    console.log('normal:', this.fruit); // 'arrow'
    var arrow = () => console.log('arrow:', this.fruit); // 繼承外層 this
    arrow();
  }
};
obj.normal(); 
// normal: arrow
// arrow: arrow

4. 構造函數 new 綁定

function Person(name) {
  this.name = name;
}
var p = new Person('Tom');
console.log(p.name); // Tom —— this 指向新創建的實例

二、prototype —— 原型對象與繼承基石

1. 每個函數都有 prototype

function Foo() {}
console.log(typeof Foo.prototype); // 'object'
console.log(Foo.prototype.constructor === Foo); // true

2. 原型鏈查找機制

function Person(name) {
  this.name = name;
}
Person.prototype.sayHi = function() {
  console.log('Hi, ' + this.name);
};

var p1 = new Person('Alice');
var p2 = new Person('Bob');

p1.sayHi(); // Hi, Alice
p2.sayHi(); // Hi, Bob

console.log(p1.__proto__ === Person.prototype); // true
console.log(Person.prototype.__proto__ === Object.prototype); // true

3. 擴展內置類型原型(慎用)

// 為 Array 添加 min 方法
Array.prototype.min = function() {
  return Math.min.apply(null, this);
};

console.log([5, 2, 9, 1].min()); // 1

// ⚠️ 陷阱:for...in 會遍歷出擴展方法
var arr = [1,2,3];
for (var key in arr) {
  console.log(key); // '0','1','2','min' 😱
}
// 解決:使用 hasOwnProperty 或 Object.keys / for...of
for (var key of Object.keys(arr)) { console.log(key); } // '0','1','2'

三、constructor —— 指向構造函數的引用

1. 默認行為

var arr = [1,2,3];
console.log(arr.constructor === Array); // true

function Foo() {}
console.log(Foo.constructor === Function); // true (函數是 Function 的實例)

var obj = new Foo();
console.log(obj.constructor === Foo); // true
console.log(obj.constructor.constructor === Function); // true

2. 重寫 prototype 導致 constructor 丟失

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

// ❌ 直接覆蓋 prototype 對象
Person.prototype = {
  getName: function() { return this.name; }
};

var p = new Person('Tom');
console.log(p.constructor === Person); // false! 指向 Object
console.log(Person.prototype.constructor === Object); // true

3. 修正 constructor

Person.prototype = {
  getName: function() { return this.name; }
};
// 手動修正
Person.prototype.constructor = Person;

var p = new Person('Tom');
console.log(p.constructor === Person); // true

4. 更好的寫法:Object.assign / 單獨賦值

// 方式一:賦值單個屬性(不覆蓋整個 prototype)
Person.prototype.getName = function() { return this.name; };
Person.prototype.setName = function(n) { this.name = n; };

// 方式二:Object.assign 合併(保留原 constructor)
Object.assign(Person.prototype, {
  getName: function() { return this.name; },
  setName: function(n) { this.name = n; }
});
// constructor 自動保持指向 Person

四、三者關係圖譜


          ┌─────────────────────┐
          │   Function.prototype│ ◄── 所有函數的 __proto__
          └──────────┬──────────┘
                     │
         ┌───────────┴───────────┐
         │                       │
    ┌────┴────┐            ┌────┴────┐
    │ Person  │            │  Array  │  (構造函數)
    └────┬────┘            └────┬────┘
         │                      │
         │ .prototype           │ .prototype
         ▼                      ▼
    ┌─────────────┐      ┌─────────────┐
    │Person.prototype│    │Array.prototype│ (原型對象)
    │.constructor│      │.constructor│
    │  ───┬─────►│      │  ───┬─────►│
    └─────│──────┘      └─────│──────┘
          │                   │
          │ new               │ new
          ▼                   ▼
    ┌──────────┐        ┌──────────┐
    │  p1      │        │  arr     │ (實例)
    └──────────┘        └──────────┘
          │                   │
          │ __proto__         │ __proto__
          └─────────┬─────────┘
                    ▼
            ┌─────────────┐
            │Object.prototype│
            └─────────────┘

五、最佳實踐總結

  1. this:永遠記住「誰調用,this 就是誰」;箭頭函數捕獲外層 this;事件回調中用 `bind` 或箭頭函數固定 this。
  2. prototype:放置共享方法/屬性;**不要**放置引用類型(數組/對象)作為默認值;擴展內置原型需極謹慎並用 `Object.defineProperty` 設置 `enumerable: false`。
  3. constructor:重寫 prototype 時必須手動修正;推薦用 `Object.assign` 或單屬性賦值避免丟失。
  4. ES6 class:語法糖,本質同上。`class A { constructor(){} method(){} }` 等價於構造函數 + prototype 掛載。

結語

`this`、`prototype`、`constructor` 是 JavaScript 面向對象的鐵三角。徹底理解它們的動態綁定、原型鏈查找、構造指向機制,是從「會用 JS」進階到「精通 JS」的必經之路。

copyright © 萬盛學電腦網 all rights reserved