萬盛學電腦網

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

JavaScript 四大調用模式與 this 綁定機制深度解析

核心概念

JavaScript 函數調用時,除顯式參數外隱式傳遞 this 和 arguments。this 綁定在調用時確定(晚綁定),取決於調用模式。

四種調用模式詳解

1. 方法調用模式


const myObject = {
  value: 0,
  increment(inc = 1) {
    this.value += typeof inc === 'number' ? inc : 1;
    return this; // 支持鏈式調用
  }
};

myObject.increment();     // this 綁定到 myObject
myObject.increment(2);    // value = 3
console.log(myObject.value); // 3

特點:this 指向調用對象,支持鏈式調用,適合面向對象設計。

2. 函數調用模式


function add(a, b) {
  return a + b;
}
const sum = add(3, 4); // this 綁定到全局對象 (瀏覽器中為 window,嚴格模式為 undefined)

缺陷:內部函數 this 丟失全局對象,ES5 解決方案:


const obj = {
  value: 1,
  double() {
    const helper = () => this.value * 2; // 箭頭函數繼承外層 this
    return helper();
  }
};

3. 構造器調用模式


function Person(name) {
  this.name = name;
}
Person.prototype.greet = function() {
  return `Hello, ${this.name}`;
};

const person = new Person('Alice'); // this 綁定到新創建對象
console.log(person.greet()); // "Hello, Alice"

原理:new 創建新對象,原型鏈連接到構造函數 prototype,this 指向新對象。

4. Apply/Call/Bind 調用模式


function greet(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`;
}

const user = { name: 'Bob' };

greet.call(user, 'Hi', '!');        // 參數列表
greet.apply(user, ['Hello', '...']); // 參數數組
const bound = greet.bind(user, 'Hey'); // 返回綁定後的新函數
bound('?'); // "Hey, Bob?"

this 綁定優先級(由高到低)

  1. new 構造器調用
  2. call/apply/bind 显式綁定
  3. 方法調用 obj.method()
  4. 函數調用 fn()(默認綁定:全局/undefined)

ES6+ 現代最佳實踐

  • 使用 class 語法糖替代構造函數
  • 回調函數優先用箭頭函數保持 this 上下文
  • 避免在回調中使用 this,改用參數傳遞
  • 嚴格模式 'use strict' 避免默認綁定到全局

經典面試陷阱


const obj = {
  value: 42,
  getValue: function() {
    return this.value;
  }
};

const fn = obj.getValue;
console.log(fn()); // undefined (非嚴格模式下 window.value)

const boundFn = obj.getValue.bind(obj);
console.log(boundFn()); // 42
copyright © 萬盛學電腦網 all rights reserved