使用 class 声明创建一个基于原型继承的具有给定名称的新类。
class Animal {
// 和 java 一样,未指定时有默认的空构造器
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const a1 = new Animal('狗蛋儿', 3);
console.log(a1);
console.log(a1.name);
console.log(a1.age);
你也可以使用类表达式定义类。但是不同于类表达式,类声明不允许再次声明已经存在的类,否则将会抛出一个类型错误。
class name [extends] {
// class body
}
在下面的例子中,我们首先定义一个名为Polygon的类,然后继承它来创建一个名为Square的类。注意,构造函数中使用的 super() 只能在构造函数中使用,并且必须在使用 this 关键字前调用。
class Polygon {
constructor(height, width) {
this.name = 'Polygon';
this.height = height;
this.width = width;
}
}
class Square extends Polygon {
constructor(length) {
super(length, length);
this.name = 'Square';
}
}
重复声明一个类会引起类型错误。
class Foo {};
class Foo {};
// Uncaught TypeError: Identifier 'Foo' has already been declared
若之前使用类表达式定义了一个类,则再次声明这个类同样会引起类型错误。
let Foo = class {};
class Foo {};
// Uncaught TypeError: Identifier 'Foo' has already been declared
通过new出来的实例,访问到的属性,叫做[实例属性]。
console.log(p1.name)
console.log(p1.age)
[静态属性] :通过构造函数,直接访问到的属性,叫做静态属性。
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
// 静态属性
Animal.info = "sss";
定义:
Animal.prototype.say = function () {
console.log('这是动物的实例方法')
}