JavaScript原型:为何仅函数会被隐式创建Prototype?
prototype Property in JavaScript? Great question—this cuts straight to the core of how JavaScript's prototype-based inheritance system was designed. Let's break this down clearly:
1. Functions Have a Dual Identity: Callable + Constructor
In JavaScript, functions aren't just for running code—they're also designed to act as constructors for creating new objects. The implicit prototype property exists specifically to enable this constructor behavior:
- When you use the
newkeyword with a function (e.g.,new MyFunc()), JavaScript automatically sets the new instance's internal[[Prototype]](accessible viaObject.getPrototypeOf(instance)) toMyFunc.prototype. - This lets all instances created by the same constructor share properties/methods stored on the prototype, which saves memory and enforces consistent behavior across instances.
Example to illustrate:
function Car(make) { this.make = make; } // We add a shared method to the implicit prototype Car.prototype.honk = function() { console.log(`${this.make} goes beep!`); }; const toyota = new Car('Toyota'); const honda = new Car('Honda'); toyota.honk(); // Toyota goes beep! honda.honk(); // Honda goes beep! // Both instances use the SAME honk method from Car.prototype
Without that implicit prototype on functions, we'd have to define honk inside the constructor (creating a new function for every instance) which is inefficient.
2. Object Literals Are Designed as Instances, Not Constructors
Object literals like const obj = {} are just syntactic sugar for new Object()—they're end-user instances, not tools for creating other objects. JavaScript doesn't expect you to use new obj() to spawn new objects (try it, and you'll get a TypeError: obj is not a constructor).
Since object literals aren't meant to be constructors, there's no need for an implicit prototype property. Their own prototype chain already points to Object.prototype (the root of most JS objects), but they don't need to serve as a prototype for other objects by default.
3. It's a Matter of Efficient Language Design
If JavaScript added an implicit prototype to every object, it would be a huge waste of memory. The vast majority of objects in typical code are just regular instances—they never get used as constructors, so that extra property would sit unused. By only adding prototype to functions, the language avoids unnecessary bloat while supporting its core inheritance model.
Note: You can manually add a prototype property to a regular object, but it won't make the object a valid constructor—JavaScript only recognizes functions as constructors that work with new.
内容的提问来源于stack exchange,提问作者Willem van der Veen

