JavaScript类语法是否默认将方法设置为原型方法?
Great question—you’re already connecting the dots between prototype inheritance, factory functions, and class syntax, which is awesome! Let’s break this down clearly.
1. Do JavaScript class methods default to prototype methods?
Absolutely! When you define methods directly inside a class (without the static keyword), they are automatically added to the class’s prototype object—exactly like how you’d manually attach methods to a constructor function’s prototype in pre-ES6 code.
Class syntax is essentially "syntactic sugar" over JavaScript’s existing prototype-based system. Here’s a direct comparison to make it concrete:
// Using ES6 class syntax class User { greet() { console.log(`Hello, ${this.name}!`); } constructor(name) { this.name = name; } } // This is equivalent to pre-ES6 constructor/prototype code function User(name) { this.name = name; } User.prototype.greet = function() { console.log(`Hello, ${this.name}!`); };
In both cases, every instance of User shares the same greet method from the prototype—no duplicate function instances clogging up memory, just like you learned with constructor functions.
2. Why do methods like method1 and method2 show up in the prototype chain of class instances?
When you create an instance using new User(), JavaScript sets the instance’s internal [[Prototype]] (visible as __proto__ in most browsers) to point directly to User.prototype.
So when you call userInstance.greet(), JavaScript first checks if the instance itself has a greet method. If it doesn’t (which it won’t, unless you explicitly define it in the constructor), it climbs up the prototype chain to User.prototype, finds the shared greet method, and executes it.
This is why all class instances can access those methods without each having its own copy—they’re sharing the single function instance stored in the class’s prototype.
As a quick contrast: if you defined a method inside the constructor like this:
class User { constructor(name) { this.name = name; // This creates a new function for EVERY instance (wastes memory!) this.instanceSpecificMethod = function() { console.log("This is only on this instance!"); }; } }
Then instanceSpecificMethod would be unique to each instance (just like the factory function pattern you mentioned that causes unnecessary memory use), whereas the class’s direct methods live on the prototype and are shared across all instances.
内容的提问来源于stack exchange,提问作者Cazineer

