function MyClass() {}
MyClass.prototype = null;
var myClass = new MyClass();
alert(myClass.toString()); // 彈出 "[object Object]"
**ES5+ 規範**:若物件的 `[[Prototype]]` 為 `null`,該物件**不繼承任何內建方法**。但 `myClass.toString()` 仍能執行,是因為 **`toString` 是 `Object.prototype` 的方法,而 `myClass` 仍是 `Object` 的實例?**
function MyClass() {}
MyClass.prototype = null;
var o = new MyClass();
console.log(Object.getPrototypeOf(o)); // null
console.log(o.toString()); // "[object Object]" <-- 為何?
console.log(o.hasOwnProperty('toString')); // false
console.log('toString' in o); // true
當物件無自身 `toString` 且原型鏈為 `null` 時,JavaScript 引擎(V8、SpiderMonkey、JavaScriptCore)為相容性,**內部仍會呼叫 `Object.prototype.toString.call(this)`** 作為預設行為。這屬於實作細節,非標準保證。
**不要依賴此行為**。若需確保物件無 `toString`,請顯式定義:
MyClass.prototype = { toString: null }; // 或 Object.create(null) 並自行定義方法
// 或
Object.defineProperty(o, 'toString', { value: undefined, configurable: true });