Class
1.类的由来
- JavaScript 语言中,生成实例对象的传统方法是通过构造函数。
- ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。
- ES6 的
class
可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法
更加清晰、更像面向对象编程的语法而已。
// ES5
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);
// ES6
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
可以看到里面有一个constructor()方法
,这就是构造方法,而this关键字则代表实例对象
。
- 1.ES6 的类,完全可以看作构造函数的另一种写法。 下面代码表明,类(Class)的数据类型就是函数,类本身就指向构造函数
- 构造函数的prototype属性,在 ES6 的“类”上面继续存在。事实上,
类的所有方法
都定义在类的prototype属性上面。
class Point {
// ...
}
typeof Point // "function"
Point === Point.prototype.constructor // true
//类的所有方法都定义在类的prototype属性上面。
class Point {
constructor() {
// ...
}
toString() {
// ...
}
toValue() {
// ...
}
}
// 等同于
Point.prototype = {
constructor() {},
toString() {},
toValue() {},
};
上面代码中,constructor()
、toString()
、toValue()
这三个方法,其实都是定义在Point.prototype上面。
因此,在类的实例上面调用方法,其实就是调用原型上的方法。
class B {}
const b = new B();
b.constructor === B.prototype.constructor // true
上面代码中,b
是B
类的实例,它的constructor()
方法就是B
类原型的constructor()方法。
由于类的方法都定义在prototype
对象上面,所以类的新方法可以添加在prototype对象
上面。Object.assign()
方法可以很方便地一次向类添加多个方法。
class Point {
constructor(){
// ...
}
}
Object.assign(Point.prototype, {
toString(){},
toValue(){}
});
prototype
对象的constructor()
属性,直接指向“类”的本身,这与 ES5 的行为是一致的。
Point.prototype.constructor === Point // true
另外,类的内部所有定义的方法,都是不可枚举的(non-enumerable)。
1.2.constructor 方法
constructor()方法
是类的默认方法,通过 new
命令生成对象实例时,自动调用该方法
。一个类必须有constructor()方法,如果没有显式定义,一个空的constructor()方法会被默认添加。
class Point {
}
// 等同于
class Point {
constructor() {}
}
上面代码中,定义了一个空的类 Point
,JavaScript 引擎会自动为它添加
一个空的constructor()方法。
constructor()方法默认返回实例对象(即this
),完全可以指定返回另外一个对象。
类必须使用 new调用
,否则会报错。这是它跟普通构造函数的一个主要区别,后者不用new也可以执行。
1.3.类的实例
- 生成类的实例的写法,与 ES5 完全一样,也是使用new命令。前面说过,如果忘记加上new,像函数那样调用Class,将会报错。
- 与 ES5 一样,实例的属性除
非显式
定义在其本身(即定义在this对象上),否则都是定义在原型上(即定义在class
上)。 - 与 ES5 一样,类的所有实例
共享一个
原型对象。
var p1 = new Point(2,3);
var p2 = new Point(3,2);
p1.__proto__ === p2.__proto__
//true
上面代码中,p1
和 p2
都是Point的实例,它们的原型都是 Point.prototype
,所以 __proto__
属性是相等的。
这也意味着,可以通过 实例的__proto__
属性为“类”添加方法。
proto 并不是语言本身的特性,这是各大厂商具体实现时添加的
私有属性
,虽然目前很多现代浏览器的 JS 引擎中都提供了这个私有属性,但依旧不建议在生产中使用
该属性,避免对环境产生依赖。生产环境中,我们可以使用Object.getPrototypeOf
方法来获取实例对象的原型,然后再来为原型添加方法/属性。
var p1 = new Point(2,3);
var p2 = new Point(3,2);
p1.__proto__.printName = function () { return 'Oops' };
p1.printName() // "Oops"
p2.printName() // "Oops"
var p3 = new Point(4,2);
p3.printName() // "Oops"
console.log(point.printName()); // "Oops" 构造函数里的原型也被修改了
上面代码在 p1
的原型上添加了一个 printName()
方法,由于 p1
的原型就是 p2
的原型,因此p2也可以调用这个方法。而且,此后新建的实例 p3
也可以调用这个方法。这意味着,使用实例的 __proto__
属性改写原型,必须相当谨慎,不推荐使用,因为这会改变“类”的原始定义,影响到所有实例。
1.4.静态成员,静态属性
-
静态成员,静态属性 : 直接添加到对象上的属性,没有添加到(construtor)原型上的属性
-
通过 console.dir() 查看
class Phone{
//声明静态属性
static name = '手机';
static change = function () {
console.log('改变');
}
}
console.dir(Phone); //
1.5.静态方法
类相当于实例的原型
,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上 static
关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“ 静态方法
”。
class Foo {
static classMethod() {
return 'hello';
}
}
Foo.classMethod() // 'hello'
var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function
上面代码中, Foo
类的 classMethod
方法前有 static
关键字,表明该方法是一个静态方法,可以直接在Foo类上调用(Foo.classMethod()
),而不是在Foo类的实例上调用。如果在实例上调用静态方法,会抛出一个错误,表示不存在该方法。
注意,如果静态方法包含 this
关键字,这个 this指的是类
,而不是实例。
class Foo {
static bar() {
this.baz();
}
static baz() {
console.log('hello');
}
baz() {
console.log('world');
}
}
Foo.bar() // hello
上面代码中,静态方法 bar
调用了 this.baz
,这里的this指的是Foo类
,而不是Foo的实例,等同于调用Foo.baz
。另外,从这个例子还可以看出,静态方法可以与非静态方法重名。
父类的静态方法,可以被子类继承。
class Foo {
static classMethod() {
return 'hello';
}
}
class Bar extends Foo {
}
Bar.classMethod() // 'hello'
上面代码中,父类Foo有一个静态方法,子类Bar可以调用这个方法。
静态方法也是可以从super对象上调用的。
class Foo {
static classMethod() {
return 'hello';
}
}
class Bar extends Foo {
static classMethod() {
return super.classMethod() + ', too';
}
}
1.6.实例属性
实例属性除了定义在 constructor()
方法里面的this上面,也可以定义在类的最顶层。
class IncreasingCounter {
constructor() {
this._count = 0;
}
get value() {
console.log('Getting the current value!');
return this._count;
}
increment() {
this._count++;
}
}
上面代码中,实例属性 this._count
定义在 constructor()
方法里面。另一种写法是,这个属性也可以定义在类的最顶层,其他都不变。
class IncreasingCounter {
_count = 0;
get value() {
console.log('Getting the current value!');
return this._count;
}
increment() {
this._count++;
}
}
上面代码中,实例属性_count与取值函数 value()
和 increment() 方法,处于同一个层级
。这时,不需要在实例属性前面加上this。
这种新写法的好处是,所有 实例对象自身的属性都定义在类的头部
,看上去比较整齐,一眼就能看出这个类有哪些实例属性。
class foo {
bar = 'hello';
baz = 'world';
constructor() {
// ...
}
}
上面的代码,一眼就能看出,foo类有两个实例属性
,一目了然。另外,写起来也比较简洁。
2.取值函数(getter)和存值函数(setter)
与 ES5 一样,在“类”的内部可以使用 get
和 set
关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为。
存值函数和取值函数是设置在属性的 Descriptor
对象上的
class CustomHTMLElement {
constructor(element) {
this.element = element;
}
get html() {
return this.element.innerHTML;
}
set html(value) {
this.element.innerHTML = value;
}
}
var descriptor = Object.getOwnPropertyDescriptor(
CustomHTMLElement.prototype, "html"
);
"get" in descriptor // true
"set" in descriptor // true
//构造函数
class Phone {
//获取价格
get price() {
return this.money;
}
//设置价格
set price(value) {
this.money = value;
console.log('价格是' + value);
}
}
//构造函数中 this 指向 实例对象
//实例对象
let huawei = new Phone();
//修改手机的价格
huawei.price = 6000;
console.log(huawei);
2.Class 的继承
2.1简介
Class 可以通过 extends
关键字实现继承,这比 ES5 的通过 修改原型链
实现继承,要清晰和方便很多。
class Point {
}
class ColorPoint extends Point {
}
- 1.
ES5
的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上面(Parent.apply(this))。 ES6
的继承机制完全不同,实质是先将父类实例对象的属性和方法,加到this上面(所以必须先调用super方法),然后再用子类的构造函数修改this。- 如果子类没有定义
constructor
方法,这个方法会被默认添加
。也就是说,不管有没有显式定义,任何一个子类都有constructor方法。 - 在
子类的构造函数
中,只有调用super
之后,才可以使用this
关键字,否则会报错。这是因为子类实例的构建,基于父类实例
,只有super方法才能调用父类实例
。
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
class ColorPoint extends Point {
constructor(x, y, color) {
this.color = color; // ReferenceError
super(x, y);
this.color = color; // 正确
}
}
上面代码中,子类的constructor
方法没有调用 super
之前,就使用this关键字,结果报错,而放在super方法之后就是正确的。
//ES5
//定义父类
function Father(name, age) {
this.name = name;
this.age = age;
}
Father.prototype.skill = function() {
console.log('他是超人');
}
Father.prototype.sing = function() {
console.log('他会唱歌');
}
//创建子类
function Son(name, age, gender, work) {
Father.call(this, name, age);
this.gender = gender;
this.work = work;
}
Son.prototype = new Father();
Son.prototype.playGame = function() {
console.log('晚上开黑');
}
let xm = new Son('大头儿子', 18, '男', '开发')
console.log(xm);
//es6
class Father {
constructor(name, age) {
this.name = name;
this.age = age;
}
//添加原型上的方法
skill() {
console.log('他是超人');
}
sing() {
console.log('他会唱歌');
}
}
//设置子类
class Son extends Father {
constructor(name, age, gender, work) {
super(name, age);
this.gender = gender;
this.work = work;
}
// 子类原型上的方法 es6 会自动拿到父元素原型上的方法
playGame() {
console.log('晚上开黑');
}
}
//实例对象
let xm = new Son('小明', 18, '男', '开发')
console.log(xm);
xm.skill();
xm.sing();
xm.playGame();
2.2super 关键字
super
这个关键字,既可以当作函数使用,也可以当作对象使用。在这两种情况下,它的用法完全不同。
super
作为函数调用时,代表父类的构造函数。ES6 要求,子类的构造函数必须执行一次super函数。
class A {}
class B extends A {
constructor() {
super();
}
}
上面代码中,子类 B
的构造函数之中的super()
,代表调用父类的构造函数。这是必须的,否则 JavaScript 引擎会报错。
注意:super
虽然代表了父类A的构造函数,但是返回的是子类B的实例,即super内部的this指的是B的实例,因此super()
在这里相当于A.prototype.constructor.call(this)
。
作为函数时,super()
只能用在子类的构造函数之中,用在其他地方就会报错。
super()
必须写在this的上面,否则会报错,这是书写规范
super
作为对象时,在普通方法中,指向父类的原型对象;在静态方法中,指向父类。
class A {
p() {
return 2;
}
}
class B extends A {
constructor() {
super();
console.log(super.p()); // 2
}
}
let b = new B();
上面代码中,子类B
当中的 super.p()
,就是将super当作一个对象使用。这时,super在普通方法之中,指向 A.prototype
,所以 super.p()
就相当于 A.prototype.p()
。
这里需要注意,由于 super
指向父类的原型对象,所以定义在父类实例上的方法或属性
,是无法通过super调用的。
class A {
constructor() {
this.p = 2;
}
}
class B extends A {
get m() {
return super.p;
}
}
let b = new B();
b.m // undefined
p
是父类A
实例的属性,super.p
就引用不到它。
如果属性定义在父类的原型对象上
,super
就可以取到。
class A {}
A.prototype.x = 2;
class B extends A {
constructor() {
super();
console.log(super.x) // 2
}
}
let b = new B();
属性x
是定义在 A.prototype
上面的,所以 super.x
可以取到它的值。
*ES6 规定,在子类普通方法中通过 super
调用父类的方法时,方法内部的this指向当前的子类实例。
class A {
constructor() {
this.x = 1;
}
print() {
console.log(this.x);
}
}
class B extends A {
constructor() {
super();
this.x = 2;
}
m() {
super.print(); //普通方法通过super调用父类方法时,方法内部this指向的是当前子类实例
}
}
let b = new B();
b.m() // 2
上面代码中,super.print()
虽然调用的是 A.prototype.print()
,但是 A.prototype.print()
内部的this
指向子类B的实例,导致输出的是2,而不是1。也就是说,实际上执行的是super.print.call(this)
。
由于this指向子类实例
,所以如果通过super对某个属性赋值
,这时super就是this
,赋值的属性会变成子类实例的属性。
class A {
constructor() {
this.x = 1;
}
}
class B extends A {
constructor() {
super();
this.x = 2;
super.x = 3;
console.log(super.x); // undefined
console.log(this.x); // 3
}
}
let b = new B();
2.3类的 prototype 属性和__proto__属性
大多数浏览器的 ES5 实现之中,每一个对象都有 __proto__
属性,指向对应的构造函数
的prototype
属性。Class 作为构造函数的语法糖,同时有prototype
属性和 __proto__
属性,因此同时存在两条继承链
。
子类的__proto__
属性,表示构造函数的继承,总是指向父类
。- 子类
prototype属性的__proto__
属性,表示方法的继承
,总是指向父类的prototype
属性。
class A {
}
class B extends A {
}
B.__proto__ === A // true
B.prototype.__proto__ === A.prototype // true
上面代码中,子类B的__proto__
属性指向父类A
,子类B的prototype
属性的__proto__
属性指向父类A的prototype
属性。
类的继承是按照下面的模式实现的
class A {
}
class B {
}
// B 的实例继承 A 的实例
Object.setPrototypeOf(B.prototype, A.prototype);
// B 继承 A 的静态属性
Object.setPrototypeOf(B, A);
const b = new B();
《对象的扩展》一章给出过Object.setPrototypeOf方法的实现。
Object.setPrototypeOf = function (obj, proto) {
obj.__proto__ = proto;
return obj;
}
因此,就得到了上面的结果。
Object.setPrototypeOf(B.prototype, A.prototype);
// 等同于
B.prototype.__proto__ = A.prototype;
Object.setPrototypeOf(B, A);
// 等同于
B.__proto__ = A;
这两条继承链,可以这样理解:
1.作为一个对象
,子类(B)的原型(__proto__属性)是父类(A)
2. 作为一个构造函数
,子类(B)
的原型对象(prototype属性)是父类的原型对象(prototype属性)的实例。
B.prototype = Object.create(A.prototype);
// 等同于
B.prototype.__proto__ = A.prototype;
extends
关键字后面可以跟多种类型的值。
class B extends A {
}
上面代码的A,只要是一个有prototype
属性的函数,就能被B继承。由于函数都有prototype属性(除了Function.prototype函数),因此A可以是任意函数。
下面,讨论两种情况。第一种,子类继承Object类
。
class A extends Object {
}
A.__proto__ === Object // true
A.prototype.__proto__ === Object.prototype // true
这种情况下,A
其实就是构造函数Object
的复制,A的实例
就是Object
的实例。
第二种情况,不存在任何继承
。
class A {
}
A.__proto__ === Function.prototype // true
A.prototype.__proto__ === Object.prototype // true
这种情况下,A
作为一个基类(即不存在任何继承),就是一个普通函数,所以直接继承Function.prototype
。但是,A调用后
返回一个空对象(即Object实例),所以A.prototype.__proto__
指向构造函数(Object)的prototype属性。
2.4实例的 proto 属性
子类实例的__proto__
属性的__proto__
属性,指向父类实例的__proto__属
性。也就是说,子类的原型的原型
,是父类的原型
。
var p1 = new Point(2, 3);
var p2 = new ColorPoint(2, 3, 'red');
p2.__proto__ === p1.__proto__ // false
p2.__proto__.__proto__ === p1.__proto__ // true
上面代码中,ColorPoint
继承了Point
,导致前者原型的原型是后者的原型。
因此,通过子类实例的__proto__.__proto__
属性,可以修改父类实例的行为
。
p2.__proto__.__proto__.printName = function () {
console.log('Ha');
};
p1.printName() // "Ha"
上面代码在ColorPoint
的实例p2
上向Point类添加方法,结果影响到了Point的实例p1。