You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

为何MDN文档称JavaScript不存在class语句,却有class语法相关章节?

Why Does MDN Say JavaScript Has No Class Statement, But Then Shows class Syntax?

Great question—this is one of the most common "wait, that contradicts itself!" moments for people learning JavaScript, especially if you’re coming from a class-based language like Java or C++. Let’s break this down clearly:

First, the context of that older statement

The line you found in the "Custom Objects" section refers to pre-ES6 JavaScript (before 2015). Back then, JavaScript truly had no class keyword at all. It’s a prototype-based language, so all object-oriented behavior was built using function constructors and prototype chains, like this:

// Pre-ES6 "class" using a function constructor
function Car(make, model) {
  this.make = make;
  this.model = model;
}
// Add methods to the prototype
Car.prototype.drive = function() {
  console.log(`Driving my ${this.make} ${this.model}`);
};

This is why the document says "contains no class statement"—that was 100% true before ES6 rolled out.

The class keyword is syntactic sugar, not a true "class" system

When ES6 launched in 2015, it introduced the class keyword to make JavaScript’s object-oriented code look more familiar to developers used to traditional OOP languages. But here’s the key: it’s just a nicer way to write the same prototype-based code under the hood.

Take the ES6 version of the Car example:

class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }
  drive() {
    console.log(`Driving my ${this.make} ${this.model}`);
  }
}

If you inspect this code in a browser’s developer tools, you’ll see that the Car class is still a function, and the drive method is still attached to Car.prototype. It doesn’t change JavaScript’s core prototype-based nature—it just hides the prototype boilerplate.

Why MDN mentions both

MDN’s documentation has evolved over time:

  • The older "Custom Objects" section was written before ES6, and while it might not have been fully updated, it’s emphasizing JavaScript’s fundamental nature (it’s still prototype-based at heart).
  • The newer "Classes" section covers the modern class syntax because it’s now a standard part of the language, even if it’s syntactic sugar.

You didn’t miss anything, and the content isn’t fully "outdated"—it’s just highlighting two layers of JavaScript: the underlying prototype system, and the modern syntax that makes it easier to work with.

内容的提问来源于stack exchange,提问作者meJustAndrew

火山引擎 最新活动