技术疑问:为何在类中必须使用foo()而非function foo()?(含JS FIDDLE)
function foo() in JavaScript Class Definitions Awesome question—this trips up a lot of folks when they first start working with ES6 classes in JavaScript! Let's unpack why this rule exists and how it works.
First, the Core Rule
ES6 classes have strict syntax requirements for defining methods. Inside a class body, you must use the concise method syntax (foo() {}) or class fields with arrow functions. Traditional function foo() declarations are explicitly disallowed and will throw a syntax error.
Let's Look at Examples
Correct Syntax (Prototype Method)
This is the standard way to define a method shared across all class instances (stored on the class prototype):
class Greeter { greet() { console.log("Hello there!"); } } const myGreeter = new Greeter(); myGreeter.greet(); // Logs "Hello there!"
Correct Syntax (Instance Method via Class Field)
You can also use arrow functions as class fields (note this creates a unique function per instance):
class Greeter { greet = () => { console.log("Hello from an arrow function!"); } } const myGreeter = new Greeter(); myGreeter.greet(); // Logs "Hello from an arrow function!"
Incorrect Syntax (Throws Error)
This will fail immediately with a syntax error, because function declarations aren't allowed in the class body:
class Greeter { // ❌ SyntaxError: Unexpected token 'function' function greet() { console.log("This won't run!"); } }
Why This Rule Exists
Syntax Consistency & Design Intent
ES6 classes were designed to provide clean, intuitive syntax for object-oriented code, moving away from clunky prototype-based patterns. The concise method syntax aligns with this goal, making class definitions more readable and consistent.Strict Mode by Default
Class bodies run in strict mode automatically. In strict mode, ambiguous or error-prone patterns (likefunctiondeclarations inside class bodies) are banned to prevent bugs.Prototype vs. Instance Methods
The concise method syntax ensures your method is added to the class's prototype, so all instances share the same function (efficient memory usage). If you really need a per-instance function (like one that bindsthisto the instance), you can assign it in the constructor or use a class field—butfunctiondeclarations in the class body aren't a valid way to do this.
Workaround If You Need Function Syntax
If you prefer the function keyword, assign the function to this inside the constructor. This creates an instance-specific method (not shared on the prototype):
class Greeter { constructor() { this.greet = function() { console.log("This works, but it's per-instance!"); }; } } const myGreeter = new Greeter(); myGreeter.greet(); // Logs "This works, but it's per-instance!"
内容的提问来源于stack exchange,提问作者otto

