💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 类 > 类(class)本质上是 es5 构造函数的另一种写法. </br> > </br> > **注意:** </br> > 1.class 定义的对象,不用 **new 关键字**声明是无法运行的,和函数加 () 是有些区别的. > 2.class 不存在变量提升. > 3.class 内部使用的是严格模式. ```javascript //es5 var Monkey = function(name, age) { this.name = name; this.age = age; this.lol = function() { console.log("i'm laughing~"); }; }; var monkey1 = new Monkey('neer', 2); monkey1.lol(); console.log("i'm" + monkey1.name + ', ' + monkey1.age + 'years old'); //es6 class Monkey { constructor(name, age) { this.name = name; this.age = age; } lol() { console.log("i'm laughing~"); } } let monkey1 = new Monkey('neer', 2); monkey1.lol(); console.log(`i'm ${monkey1.name}, ${monkey1.age} years old`); //子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。 // 类的继承 class Person { constructor(name, gender) { this.name = name; this.gender = gender; } introduction() { console.log(`my name is ${this.name} and i'm a ${this.gender}`); } } class Son extends Person { constructor(name, gender, age) { super(name, gender); this.age = age; } call() { console.log( `i'm ${this.name}'s son, my father is ${this.gender},i was ${ this.age } years old ` ); } } ```