能否将Object.prototype设置为Null?JavaScript原型技术咨询
null to Object.prototype, or turn Object.prototype itself into null? Great question—this digs into some of JavaScript's core prototype system rules, so let's break it down clearly.
1. Can you assign null to Object.prototype?
Short answer: No, you can't do this successfully.
Object.prototype is a built-in non-writable property of the Object constructor. Here's what plays out in different execution modes:
- In non-strict mode: Trying to run
Object.prototype = null;will silently fail—your assignment gets ignored entirely, andObject.prototypestays the original prototype object. - In strict mode: The same line will throw a
TypeError: Cannot assign to read-only property 'prototype' of function 'function Object() { [native code] }', since strict mode enforces write restrictions for built-in protected properties.
You can test this with a quick snippet:
'use strict'; try { Object.prototype = null; } catch (e) { console.log(e); // Logs the TypeError mentioned above } console.log(Object.prototype); // Still outputs the original prototype object, not null
2. Can you make Object.prototype itself become null?
Again, no. Object.prototype is inherently an object—it's the root prototype for nearly all JavaScript objects. You can't convert an existing object into the null primitive; they're fundamentally distinct types.
You could modify or delete individual properties on Object.prototype (though this is extremely bad practice that will break most JS code), like:
// Don't ever do this in real code! delete Object.prototype.toString; console.log(Object.prototype.toString); // Outputs undefined
But even if you strip all its properties, Object.prototype remains an empty object—not null.
Why this matters for your original code example
The pattern Object.prototype.toString.call(a, this) relies on Object.prototype being intact. If you somehow broke Object.prototype (by deleting methods or tampering with it), this line would throw an error because toString would no longer exist on the prototype. Libraries use this approach because it skips any custom toString methods defined on the object a, giving a reliable way to check the object's actual underlying type.
内容的提问来源于stack exchange,提问作者Shubham

