一、class 是什么?
class 是 ECMAScript 2015 引入的类对象,其继承特性也是基于原型链。
1、定义类
// 语法一
class name [extends] {
// class body
}
// 语法二
const MyClass = class [className] [extends] {
// class body
};
2、简单实例
let Foo = class {
constructor() {}
bar() {
return "Hello World!";
}
};
let instance = new Foo();
instance.bar();
二、class 特性
1、constructor
功能:constructor() 是初始化 class对象 的特殊函数,称之为构造函数。
- 一个类中只能有一个名为 constructor 的函数;
- 如果不指定 constructor ,会使用默认构造函数;
- constructor 中,可以用 super 调用父类的构造函数、属性、函数,但必须在this之前。
// 1、语法
constructor([arguments]) { ... }
// 2、类的默认构造函数
constructor() {}
// 3、子类的默认构造函数
constructor(...args) {
super(...args);
}
// 使用实例
class Polygon {
constructor() {
this.name = "Polygon";
}
}
class Square extends Polygon {
constructor() {
super();
}
}
let newInstance = new Square();
console.log(newInstance.name); //Polygon
2、extends
功能:用于表示创建某个类的子类,实现继承。
// 语法
class ChildClass extends ParentClass { ... }
// 实例
class myDate extends Date {
constructor() {
super();
}
getFormattedDate() {
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear();
}
}
3、super
功能:用于调用父类构造函数、属性、函数。只能在构造函数中使用且在this之前。
// 语法
super([arguments]); // 调用父类构造函数
super.functionOnParent([arguments]);// 调用父类函数
super.property;// 调用父类属性
- 简单实例
class Polygon {
constructor(height, width) {
this.name = 'Rectangle';
this.height = height;
this.width = width;
}
sayName() {
console.log('Hi, I am a ', this.name + '.');
}
get area() {
return this.height * this.width;
}
set area(value) {
this._area = value;
}
}
class Square extends Polygon {
constructor(length) {
this.height; // ReferenceError,super 需要先被调用!
// 这里,它调用父类的构造函数的,
// 作为Polygon 的 height, width
super(length, length);
// 注意: 在派生的类中, 在你可以使用'this'之前, 必须先调用super()。
// 忽略这, 这将导致引用错误。
this.name = 'Square';
}
}
- super 调用父类静态函数
class Rectangle {
constructor() {}
static logNbSides() {
return 'I have 4 sides';
}
}
class Square extends Rectangle {
constructor() {}
static logDescription() {
return super.logNbSides() + ' which are all equal';
}
}
Square.logDescription(); // 'I have 4 sides which are all equal'
- 删除 super 的属性,会有异常
class Base {
constructor() {}
foo() {}
}
class Derived extends Base {
constructor() {}
delete() {
delete super.foo; // this is bad
}
}
new Derived().delete(); // ReferenceError: invalid delete involving 'super'.
- 原型链中使用super
var obj1 = {
method1() {
console.log("method 1");
}
}
var obj2 = {
method2() {
super.method1();
}
}
Object.setPrototypeOf(obj2, obj1);
obj2.method2(); // logs "method 1"
4、new
用于创建用户定义的对象实例 或 创建具有构造函数的内置对象实例。更多...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。