JavaScript 標準庫提供許多可見的建構器(Object、Array、Date...),但引擎內部還存在一類使用者程式碼無法直接建構的特殊型別。它們只在特定情境由引擎自動產生,且功能常被裁減。本文深入剖析兩大代表:**Arguments** 與 **Function.prototype.bind 回傳的特殊函式**。
new Arguments() → TypeError。arguments 存取。0...length-1 與 length 屬性。push/pop/map/filter 等陣列方法。Rest 參數 可完美替代。function func(a, b, c) {
console.log(arguments[0]); // 1
console.log(arguments.length); // 3
// arguments.push(4); // TypeError: arguments.push is not a function
// 轉真正陣列:
const args = Array.from(arguments); // ES6
// const args = [].slice.call(arguments); // ES5
}
func(1, 2, 3);
'use strict';
function strict(a) {
a = 10;
console.log(arguments[0]); // 1(不再同步映射)
// arguments.callee 禁止存取
}
strict(1);
bind 回傳的特殊函式function greet(role) {
console.log(`${this.name} is a ${role}`);
}
const user = { name: 'Alice' };
const bound = greet.bind(user, 'developer');
bound(); // "Alice is a developer"
prototype 屬性為 undefinedconsole.log(bound.prototype); // undefined
console.log(greet.prototype); // { constructor: f greet() } 正常函式有 prototype
「
bind回傳的函式物件沒有 prototype 屬性。」此設計意圖:綁定函式不打算作為建構器使用(new bound()拋 TypeError),故不需 prototype 實現繼承。
bound.length = 原函式參數數 - 已綁定參數數(不含 this)。bound.name = "bound " + 原函式名稱。Function.prototype.bind 偵測是否為 bound 函式(無標準 API),可用 func.name.startsWith('bound ') 近似判斷。| 型別 | 產生時機 | 特徵 |
|---|---|---|
CallSite (Error.prepareStackTrace) |
Error.captureStackTrace 或拋出錯誤 |
堆疊幀資訊,含 getFileName()、getLineNumber() 等 |
| Module Namespace Object | import * as ns from 'mod' |
不可擴展、屬性唯讀、無 [[Construct]] |
Internal Slots 物件 (如 [[PromiseState]]) |
Promise、Generator、AsyncFunction 等內建實例 | 不可直接存取,僅透過標準方法間接操作 |
| Host 物件 (DOM nodes, XMLHttpRequest...) | 瀏覽器環境提供 | 行為由 WebIDL 定義,非純 ECMAScript 物件 |
...args) 取代 arguments:獲得真陣列、支援解構、語意明確。bind 回傳函式使用 new:會拋錯;若需建構器綁定,請用 class extends 或手工包裝。JSON.stringify 會忽略 arguments 的非索引屬性;lodash.cloneDeep 會保留 bound 函式的 length/name 但無法還原綁定上下文。bind 回傳型別為 ThisParameterType & OmitThisParameter ,型別系統可正確推導參數減少。理解「不可見型別」存在的理由與限制,能幫助你在設計 API、除錯堆疊、效能調優時做出更精準的判斷。現代 JS 開發中,盡量以標準高階 API(Rest 參數、箭頭函式、Array.from)取代對內部物件的直接依賴。