萬盛學電腦網

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

JavaScript 中 self 與 this 深度解析:原型鏈、構造函數、apply/call、arguments 對象

引子:Prototype.js 源碼片段

var Class = {
    create: function() {
        return function() {
            this.initialize.apply(this, arguments);
        };
    }
};

var A = Class.create();
A.prototype = {
    initialize: function(v) { this.value = v; },
    showValue: function() { alert(this.value); }
};

var a = new A('helloWorld!');
a.showValue(); // 彈出 helloWorld!

這段代碼涉及:構造函數、原型鏈、`apply`、`arguments`、`this` 指向。下面逐層拆解。

一、JavaScript 面向對象基礎

1. 函數即類,new 即實例化

var Person = function(name) {
    this.name = name;           // 實例屬性
    this.sayHi = function() {   // 實例方法(每個實例擁有副本)
        alert(this.name);
    };
};

var p1 = new Person('Tom'); // p1 是 Person 實例,構造函數內 this 指向 p1
var p2 = Person('Jerry');   // 無 new,當作普通函數執行,this 指向 window → 污染全局

2. 原型對象共享方法

Person.prototype.sayHi = function() { // 所有實例共享同一個函數
    alert(this.name);
};
var p3 = new Person('Bob');
p3.sayHi(); // Bob

二、Prototype.js 的 Class.create 機制

1. create 返回的構造函數

function() {
    this.initialize.apply(this, arguments);
}
  • 調用 `new A('hello')` 時,`this` 指向新創建的實例 `a`。
  • 隨即調用 `this.initialize.apply(this, arguments)`:
  • `this`(第一個參數)→ 綁定 `initialize` 內部的 `this` 為實例 `a`。
  • `arguments`(第二個參數)→ 實參列表的類數組對象,傳給 `initialize`。

2. initialize 的角色

約定俗成的「構造器初始化方法」,在 `A.prototype` 中定義:

initialize: function(v) { this.value = v; }

因此 `new A('hello')` 相當於執行 `a.value = 'hello'`。

三、call() 與 apply() —— 改變 this 指向

方法語法參數傳遞適用場景
callfn.call(thisArg, arg1, arg2, ...)逐個列舉參數數量固定、明確
applyfn.apply(thisArg, [argsArray])數組/類數組參數數量不定、已有數組

示例

function greet(greeting, punctuation) {
    console.log(greeting + ', ' + this.name + punctuation);
}
var person = { name: 'Alice' };

greet.call(person, 'Hello', '!');       // Hello, Alice!
greet.apply(person, ['Hi', '?']);       // Hi, Alice?

// 經典應用:數組求最大值
var max = Math.max.apply(null, [1, 5, 3]); // 5

四、arguments 對象 —— 函數內部的類數組

  • 僅在**函數內部**可用。
  • 包含調用時傳入的所有實參,`arguments[0]`、`arguments[1]`...。
  • `arguments.length` 為實參個數。
  • **非數組**,但可借用數組方法:`Array.prototype.slice.call(arguments)` → 真數組。
  • ES6 剩餘參數 `...args` 可完美替代,且是真數組。
function test() {
    console.log(typeof arguments); // "object"
    for (var i = 0; i < arguments.length; i++) {
        console.log(arguments[i]);
    }
}
test("1", "2", "3"); // 依次輸出 1 2 3

五、self 與 this 的區別

概念含義典型用法
this函數執行時的上下文對象,由**調用方式**決定構造函數、方法調用、事件處理器、call/apply/bind 綁定
self**非關鍵字**,慣例變量名,用於在閉包/回調中保存外層 `this``var self = this;` 在異步回調、定時器、事件處理器中訪問外層上下文

經典 self 用法

var obj = {
    name: 'Outer',
    asyncFunc: function() {
        var self = this; // 保存外層 this
        setTimeout(function() {
            console.log(self.name); // 'Outer' (若直接用 this 會指向 window)
        }, 100);
    }
};
obj.asyncFunc();

現代寫法:箭頭函數自動捕獲外層 `this`,無需 `self`:

asyncFunc: function() {
    setTimeout(() => {
        console.log(this.name); // 箭頭函數無 this,沿用外層
    }, 100);
}

六、綜合圖解:原型鏈與構造調用流程

new A('hello')
   │
   ▼
創建新對象 a,a.__proto__ = A.prototype
   │
   ▼
執行構造函數:function() { this.initialize.apply(this, arguments); }
   │
   ▼
this → a
arguments → ['hello']
   │
   ▼
a.initialize.apply(a, ['hello'])
   │
   ▼
initialize 內部:this.value = 'hello'  → a.value = 'hello'
   │
   ▼
返回 a(隱式)

七、總結

  • this:動態綁定,誰調用指向誰(箭頭函數除外)。
  • self:變量約定,靜態捕獲外層 `this`,解決回調中 `this` 丟失。
  • apply/call:手動指定 `this` 與參數,`apply` 接收數組適合參數不定場景(如 `initialize.apply(this, arguments)`)。
  • arguments:函數內部類數組,ES6 用 `...rest` 替代。
  • 原型鏈:實例 → `constructor.prototype` → `Object.prototype` → `null`,屬性查找順序。
copyright © 萬盛學電腦網 all rights reserved