文章目录
前言
在 Canvas 项目中我们一般是使用面向对象的方式进行开发的,因此我们需要全面了解面向对象 class 类的使用。为此我通过 阮一峰 ECMScript 6 入门 中的 class 基本语法和继承进行学习。
为了更好的实现面向对象编程,降低代码的冗余度,es6 推出了 class 类的概念。他实际上是一种语法糖,本质上利用的还是原型和构造函数的概念。
类的由来
JavaScript 语言中,生成实例对象的传统方法是通过构造函数。下面是一个例子
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function () {
return '(' + this.x + ',' + this.y + ')';
};
var p = new Point(1, 2);
上面这种写法跟传统的面向对象语言(比如 C++ 和 Java)差异很大,为此 ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
下面举例说明 类和构造函数的关系:
/* ES6 的类,完全可以看作构造函数的另一种写法。 */
class Point {
// ...
}
typeof Point // "function" 类的数据类型就是函数
Point === Point.prototype.constructor // true 类本身就指向构造函数
const p = new Point(1, 2)
p.__proto__ === Point.prototype // true
/* 构造函数的prototype属性,在 ES6 的“类”上面继续存在。事实上,类的所有方法都定义在类的prototype属性上面。 */
class Point {
constructor() {}
toString() {}
toValue() {}
}
// 等同于
Point.prototype = {
constructor() {},
toString() {},
toValue() {},
};
b.constructor === B.prototype.constructor // true 实例的构造函数,指向类本身
constructor 方法
constructor 方法是类的默认方法,通过 new 命令生成对象实例时,自动调用该方法。一个类必须有 constructor 方法,如果没有显式定义,一个空的 constructor 方法会被默认添加。
class Point {
}
// 等同于
class Point {
constructor(x, y) {}
}
类的实例
类的属性和方法,除非显式定义在其本身(即定义在 this 对象上),否则都是定义在原型上(即定义在 class 上)。
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
var point = new Point(2, 3);
point.toString() // (2, 3)
// hasOwnProperty 检查的是对象自身属性
point.hasOwnProperty('x') // true
point.hasOwnProperty('y') // true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') // true
实例属性
实例属性指的是定义在实例对象上的属性。
实例属性是在实例对象创建时创建的,实例属性是实例对象私有的,实例对象只能访问自己创建的实例属性。
// 原来的写法 属性定义在 constructor 中
class IncreasingCounter {
constructor() {
this._count = 0;
}
get value() {
console.log('Getting the current value!');
return this._count;
}
increment() {
this._count++;
}
}
// 新写法 这个属性也可以定义在类的最顶层,其他都不变。
class IncreasingCounter {
_count = 0;
get value() {
console.log('Getting the current value!');
return this._count;
}
increment() {
this._count++;
}
}
取值函数(getter)和存值函数(setter)
类的内部可以使用 get 和 set 关键字,定义取值函数和存值函数。
class MyClass {
_prop = '';
constructor() {
// ...
}
get prop() {
console.log('getter');
return this._prop;
}
set prop(value) {
console.log('setter');
this._prop = value;
}
}
let inst = new MyClass();
inst.prop = 123; // setter: 123
inst.prop // 'getter'
静态方法
类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。
class Foo {
static classMethod() {
return 'hello';
}
}
Foo.classMethod(); // 'hello'
var foo = new Foo();
foo.classMethod(); // TypeError: foo.classMethod is not a function
如果静态方法包含this关键字,这个this指的是类,而不是实例。另外,静态方法可以与非静态方法重名。
class Foo {
static bar() {
this.baz();
}
static baz() {
console.log('hello');
}
baz() {
console.log('world');
}
}
Foo.bar() // hello
父类的静态方法,可以被子类继承。
class Foo {
static classMethod() {
return 'hello';
}
}
class Bar extends Foo {
}
Bar.classMethod() // 'hello'
静态方法也是可以从super对象上调用的。
class Foo {
static classMethod() {
return 'hello';
}
}
class Bar extends Foo {
static classMethod() {
return super.classMethod() + ', too';
}
}
Bar.classMethod() // "hello, too"
静态属性
静态属性指的是 Class 本身的属性,即Class.propName,而不是定义在实例对象(this)上的属性。
// 老写法
class Foo {
}
Foo.prop = 1;
// 新写法
class Foo {
static prop = 1;
}
私有方法和私有属性
私有方法和私有属性,是只能在类的内部访问的方法和属性,外部不能访问。这是常见需求,有利于代码的封装,但早期的 ES6 不提供,只能通过变通方法模拟实现。
class MyClass {
constructor() {
this._privateField = '私有属性';
}
_privateMethod() {
console.log('私有方法');
}
publicMethod() {
console.log(this._privateField);
this._privateMethod();
}
}
ES2022 正式支持的私有属性和方法 (推荐):
class MyClass {
#privateField = '私有属性';
#privateMethod() {
console.log('私有方法');
}
publicMethod() {
console.log(this.#privateField);
this.#privateMethod();
}
}
类的继承
简介
Class 可以通过extends关键字实现继承,让子类继承父类的属性和方法。extends 的写法比 ES5 的原型链继承,要清晰和方便很多。
class Point { /* ... */ }
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y); // 调用父类的constructor(x, y)
this.color = color;
}
toString() {
return this.color + ' ' + super.toString(); // 调用父类的toString()
}
}
ES6 规定,子类必须在constructor()方法中调用super(),否则就会报错。这是因为子类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,添加子类自己的实例属性和方法。如果不调用super()方法,子类就得不到自己的this对象。
私有属性和私有方法的继承
父类所有的属性和方法,都会被子类继承,除了私有的属性和方法。
子类无法继承父类的私有属性,或者说,私有属性只能在定义它的 class 里面使用。
class Foo {
#p = 1;
#m() {
console.log('hello');
}
}
class Bar extends Foo {
constructor() {
super();
console.log(this.#p); // 报错
this.#m(); // 报错
}
}
如果父类定义了私有属性的读写方法,子类就可以通过这些方法,读写私有属性。
class Foo {
#p = 1;
get p() {
return this.#p;
}
}
class Bar extends Foo {
constructor() {
super();
console.log(this.p); // 1
}
}
静态属性和静态方法的继承
注意,静态属性是通过浅拷贝实现继承的。
class A { static foo = 100; }
class B extends A {
constructor() {
super();
B.foo--;
}
}
const b = new B();
B.foo // 99
A.foo // 100
上面示例中,foo是 A 类的静态属性,B 类继承了 A 类,因此也继承了这个属性。但是,在 B 类内部操作B.foo这个静态属性,影响不到A.foo,原因就是 B 类继承静态属性时,会采用浅拷贝,拷贝父类静态属性的值,因此A.foo和B.foo是两个彼此独立的属性。
但是,由于这种拷贝是浅拷贝,如果父类的静态属性的值是一个对象,那么子类的静态属性也会指向这个对象,因为浅拷贝只会拷贝对象的内存地址。
class A {
static foo = { n: 100 };
}
class B extends A {
constructor() {
super();
B.foo.n--;
}
}
const b = new B();
B.foo.n // 99
A.foo.n // 99
上面示例中,A.foo的值是一个对象,浅拷贝导致B.foo和A.foo指向同一个对象。所以,子类B修改这个对象的属性值,会影响到父类A。
类的注意点
不存在提升
类不存在变量提升(hoist),这一点与 ES5 完全不同。
new Foo(); // ReferenceError
class Foo {}
上面代码中,Foo类使用在前,定义在后,这样会报错,因为 ES6 不会把类的声明提升到代码头部。这种规定的原因与下文要提到的继承有关,必须保证子类在父类之后定义。
{
let Foo = class {};
class Bar extends Foo {
}
}
上面的代码不会报错,因为Bar继承Foo的时候,Foo已经有定义了。但是,如果存在class的提升,上面代码就会报错,因为class会被提升到代码头部,而定义Foo的那一行没有提升,导致Bar继承Foo的时候,Foo还没有定义。
name 属性
由于本质上,ES6 的类只是 ES5 的构造函数的一层包装,所以函数的许多特性都被Class继承,包括name属性。name属性总是返回紧跟在class关键字后面的类名。
class Point {}
Point.name // "Point"
内存占用
实例属性和实例方法(定义在 this 上的):每个实例都会有自己独立的方法和属性副本,要是创建大量实例,会占用较多内存。
原型属性和原型方法(定义在 prototype 上):所有实例共享同一个原型对象,只在内存中存在一份,所以内存占用相对较少。
静态属性和静态方法:静态方法属于类本身,只在内存中存在一份,不随实例的创建而复制,内存占用也较少。
class MyClass {
// 实例属性
instanceProperty = '实例属性';
// 静态属性
static staticProperty = '静态属性';
constructor(value) {
// 实例属性(通过构造函数初始化)
this.constructorProperty = value;
}
// 实例方法
instanceMethod() {
console.log('实例方法:', this.instanceProperty);
}
// 静态方法
static staticMethod() {
console.log('静态方法:', this.staticProperty);
}
}
// 原型方法
MyClass.prototype.prototypeMethod = function() {
console.log('原型方法:', this.instanceProperty);
};
// 原型属性
MyClass.prototype.prototypeProperty = '原型属性';
// 使用示例
const obj = new MyClass('构造属性');
obj.instanceMethod(); // 调用实例方法
obj.prototypeMethod(); // 调用原型方法
MyClass.staticMethod(); // 调用静态方法
console.log(obj.constructorProperty); // 访问实例属性
console.log(obj.prototypeProperty); // 访问原型属性
console.log(MyClass.staticProperty); // 访问静态属性
关键点说明:
- 实例属性和方法 :每个实例独有的属性和方法
- 静态属性和方法 :属于类本身,通过类名直接访问
- 原型属性和方法 :所有实例共享,定义在类的 prototype 上
- 实例可以访问原型属性和方法,但不能访问静态属性和方法
实例方法 instanceMethod 和原型方法 prototypeMethod 的主要区别如下
1.定义方式不同
2.内存占用不同
- 实例方法:每个实例都会创建自己的方法副本,占用更多内存
- 原型方法:所有实例共享同一个方法,内存效率更高
3.继承行为不同
- 实例方法:可以被派生类通过 super 调用
- 原型方法:只能通过原型链访问
4.性能差异
- 实例方法:查找速度更快(直接存在于实例上)
- 原型方法:查找速度稍慢(需要通过原型链查找)
5.使用场景
- 实例方法:适合需要访问实例私有字段或需要被子类重写的方法
- 原型方法:适合多个实例共享的通用方法
实际开发中,ES6 class 语法中定义的方法默认就是实例方法,而原型方法需要显式地添加到 prototype 上。
当前项目中的使用
class Shape {
// 构造函数
constructor(template, doNotCheck) {
this.initProperty()
this.setTemplate(template, doNotCheck)
}
// 访问器属性(getter/setter)
get assembly() {
return Shape
}
get width() {
return this.propMap.width
}
set width(val) {
let re = Shape.Fun.assignInteger(this, 'width', val)
if (re) {
this.afterSizeChangeWrapper()
}
}
// 实例方法
initProperty() {
// 实例属性
this.backObject = {}
this._id = this.assembly.Type + Helper.Lib.getId()
this.propMap = {
page: null,
parent: null,
width: 10,
height: 10,
}
}
setTemplate(template, doNotCheck) {
if (this.isDisposed) return
Shape.Fun.setTemplate(this, template, doNotCheck)
}
dispose() {}
}
// 静态属性
Shape.type = 'Shape'
Shape.Style = {}
Shape.Template = {}
// 静态方法
Shape.Fun = {
render() {}
}
export default Shape