萬盛學電腦網

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

JavaScript 普通函數 vs 構造函數深度對比:new 運算符內部機制、返回值陷阱、call/apply 借用模式

核心區別速覽

特性普通函數構造函數
調用方式fn()new Fn()
this 指向全局/undefined新創建的實例對象
返回值任意值,return 生效默認返回 this;返回對象則覆蓋,返回基本類型忽略
命名慣例駝峰小寫 camelCase帕斯卡大寫 PascalCase
prototype有但通常不使用核心:掛載共享方法

new 運算符四步驟(模擬實現)

function myNew(Constructor, ...args) {
  // 1. 創建空對象,原型指向構造函數 prototype
  var obj = Object.create(Constructor.prototype);
  // 2. 執行構造函數,this 綁定 obj
  var result = Constructor.apply(obj, args);
  // 3. 返回值判斷
  return (result !== null && (typeof result === 'object' || typeof result === 'function'))
    ? result : obj;
}

// 使用
function Person(name) { this.name = name; }
var p = myNew(Person, 'Lee');
console.log(p.name); // Lee
console.log(p instanceof Person); // true

構造函數返回值陷阱

function A() { return 'primitive'; }
function B() { return { custom: true }; }
function C() { return undefined; } // 或無 return

new A(); // 返回 A 實例(忽略基本類型返回值)
new B(); // 返回 {custom: true}(對象返回值覆蓋 this)
new C(); // 返回 C 實例

構造函數能當普通函數調用嗎?

function Box(name) { this.name = name; }
Box('test'); // 非嚴格模式:this=window → window.name='test' 污染全局
            // 嚴格模式:this=undefined → TypeError

// 意外調用防護模式
function Box(name) {
  if (!(this instanceof Box)) return new Box(name); // 自動修正
  this.name = name;
}
Box('test'); // 正常返回實例
new Box('test'); // 正常

call / apply / bind 借用模式詳解

場景:對象冒充實現繼承

function Animal(name) { this.name = name; }
Animal.prototype.say = function() { console.log(this.name); };

function Cat(name, color) {
  Animal.call(this, name); // 借用父構造函數初始化屬性
  this.color = color;
}
Cat.prototype = Object.create(Animal.prototype); // 原型鏈繼承方法
Cat.prototype.constructor = Cat;

var cat = new Cat('Kitty', 'white');
cat.say(); // Kitty

call/apply 區別

  • fn.call(ctx, arg1, arg2...):參數列表展開
  • fn.apply(ctx, [arg1, arg2...]):參數數組
  • 性能差異微乎其微,按參數形式選擇

bind 進階:柯里化 / 預設參數

function mul(a, b, c) { return a * b * c; }
var double = mul.bind(null, 2);     // 固定 a=2
var triple = double.bind(null, 3);  // 固定 b=3 → 2*3*c
triple(5); // 30

箭頭函數與構造函數

  • 箭頭函數 **不能** 用作構造函數(無 prototype、無 this 綁定、new 報錯)
  • 箭頭函數 **不能** 用 call/apply/bind 改變 this(詞法綁定)

最佳實踐總結

  1. 構造函數首字母大寫,配合 new 使用
  2. 共享方法掛載 prototype,實例屬性寫在構造函數
  3. 繼承用 class extends(ES6+)或 寄生組合式(ES5)
  4. 防呆:構造函數首行加 if(!(this instanceof Fn)) return new Fn(...args)
  5. 避免在構造函數中返回對象(除非刻意工廠模式)
  6. 回調函數用箭頭函數保持外層 this
copyright © 萬盛學電腦網 all rights reserved