一、ES6中类的深入学习及ES6实现继承(babel,js中的多态,字面量的增强,解构)
Lyk 2022/8/2 ES6class关键字类的实例方法类的访问器方法static关键字类的静态方法ES6实现继承extends关键字super关键字babel工具js多态字面量的增强写法数组的解构对象的解构
# 1、ES6中类的深入学习-class关键字定义类
# 1.1.认识class定义类
- 我们会发现,按照前面的构造函数形式创建 类,不仅仅和编写普通的函数过于相似,而且代码并不容易理解。
- 在ES6(ECMAScript2015)新的标准中使用了class关键字来直接定义类;
- 但是类本质上依然是前面所讲的构造函数、原型链的语法糖而已;
- 所以学好了前面的构造函数、原型链更有利于我们理解类的概念和继承关系;
- 那么,如何使用class来定义一个类呢?
- 可以使用两种方式来声明类:类声明和类表达式
class Person{}//类声明
var Student = class {}//类表达式
1
2
2
# 1.2.类和构造函数的异同
- 我们来研究一下类的一些特性:
- 你会发现它和我们的构造函数的特性其实是一致的;
class Person{}
var p = new Person()
console.log(Person)//class Person{ }
console.log(Person.prototype)//{constructor: ƒ}
console.log(Person.prototype.constructor)//class Person{ }
console.log(p.__proto__ === Person.prototype)//true
console.log(typeof Person)//function
1
2
3
4
5
6
7
2
3
4
5
6
7
# 1.3.类的构造函数
- 如果我们希望在创建对象的时候给类传递一些参数,这个时候应该如何做呢?
- 每个类都可以有一个自己的构造函数(方法),这个方法的名称是固定的constructor;
- 当我们通过new操作符,操作一个类的时候会调用这个类的构造函数constructor;
- 每个类只能有一个构造函数,如果包含多个构造函数,那么会抛出异常;
- 当我们通过new关键字操作类的时候,会调用这个constructor函数,并且执行如下操作:
- 在内存中创建一个新的对象(空对象);
- 这个对象内部的[[prototype]]属性会被赋值为该类的prototype属性;
- 构造函数内部的this,会指向创建出来的新对象;
- 执行构造函数的内部代码(函数体代码);
- 如果构造函数没有返回非空对象,则返回创建出来的新对象;
class Person {
constructor(name,age) {
this.name = name,
this.age = age
}
}
var p = new Person('kobe',39)
1
2
3
4
5
6
7
2
3
4
5
6
7
# 1.4.类的实例方法
- 在上面我们定义的属性都是直接放到了this上,也就意味着它是放到了创建出来的新对象中:
- 在前面我们说过对于实例的方法,我们是希望放到原型上的,这样可以被多个实例来共享;
- 这个时候我们可以直接在类中定义;
class Person {
constructor(name, age) {
this.name = name,
this.age = age
}
running() {//相当ES5中:Person.prototype.running = function(){console.log(this.name, 'running')}
console.log(this.name, 'running')
}
eating() {
console.log(this.name, 'eating')
}
}
var p = new Person('kobe', 39)
p.running()//kobe running
p.eating()//kobe eating
console.log(Person.prototype)//{constructor: ƒ, running: ƒ, eating: ƒ}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 1.5.类的访问器方法
- 我们之前讲对象的属性描述符时有讲过对象可以添加setter和getter函数的,那么类也是可以的:
class Person {
constructor(name) {
this._name = name
}
set name(newName) {
console.log('调用了name的setter方法')
this._name = newName
}
get name() {
console.log('调用了name的getter方法')
return this._name
}
}
var p = new Person('kobe')
p.name = 'james'//该语句会调用Person.prototype的set name方法(即将this._name设置成james,而这里的set name方法是p对象调的,所以这里的this是p对象)
console.log(p)//Person {_name: 'james'}
console.log(p.name)//james; 该语句会调用Person.prototype的get name方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 1.6.类的静态方法
- 静态方法通常用于定义直接使用类来执行的方法(类方法),不需要有类的实例,使用static关键字来定义:
class Person {
constructor(name, age) {
this.name = name,
this.age = age
}
running() {//实例方法
console.log(this.name, 'running')
}
static createRandomObj() {//类方法
return new Person(this.name, Math.floor(Math.random() * 100))
}
}
var RandomObj = Person.createRandomObj()
console.log(RandomObj)//Person {name: 'Person', age: 62} 这里age是个0~100的随机数
RandomObj.running()//Person running
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 1.7.ES6类的继承 - extends
- 前面我们花了很大的篇幅讨论了在ES5中实现继承的方案,虽然最终实现了相对满意的继承机制,但是过程却依然是非常繁琐的。
- 在ES6中新增了使用extends关键字,可以方便的帮助我们实现继承:
- 注意:子类可以继承父类的实例方法,也可以继承父类的静态方法(即类方法)
class Person {
running() {
console.log('running')
}
static yk() {
console.log('lyk')
}
}
class Student extends Person{}
var stu = new Student
stu.running()//running
Student.yk()//lyk
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 1.8.super关键字
我们会发现在上面的代码中我使用了一个super关键字,这个super关键字有不同的使用方式:
注意:在子(派生)类的构造函数中使用this或者返回默认对象之前,必须先通过super调用父类的构造函数!
super的使用位置有三个:子类的构造函数、实例方法、静态方法;
class Animal {
constructor(name, age) {
this.name = name,
this.age = age
}
running() {
console.log("running")
}
eating() {
console.log("eating")
}
static sleep() {
console.log("static animal sleep")
}
}
class Dog extends Animal {
constructor(name, age, weight) {
// 注意:在子(派生)类的构造函数中使用this或者返回默认对象之前,必须先通过super调用父类的构造函数!
super(name, age)//这里super必须放在最上面进行调用,否则会抛出错误
this.weight = weight
}
// 子类如果对于父类的方法实现不满足(继承过来的方法)
// 重新实现称之为重写(父类方法的重写)
running() {
console.log("dog四条腿")
// 调用父类的方法
super.running()
}
static sleep() {
console.log("趴着")
// 调用父类的静态方法
super.sleep()
}
}
var dog = new Dog()
dog.running()//dog四条腿 --> running
dog.eating()//eating
Dog.sleep()//趴着 --> static animal sleep
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 1.9.继承内置类
- 我们也可以让我们的类继承自内置类,比如Array:
class YkArray extends Array {
lastItem() {//继承了内置类Array 并扩展了lastItem实例方法
return this[this.length - 1]
}
}
var arr = new YkArray(10, 20, 30, 40, 50, 60)
console.log(arr.lastItem())//60
arr.push(66)
console.log(arr)//YkArray(7) [10, 20, 30, 40, 50, 60, 66]
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 1.10.类的混入mixin
- JavaScript的类只支持单继承:也就是只能有一个父类
- 那么在开发中我们我们需要在一个类中添加更多相似的功能时,应该如何来做呢?
- 这个时候我们可以使用混入(mixin);
// JavaScript只支持单继承(不支持多继承)
function mixinAnimal(BaseClass) {
return class extends BaseClass {
running() {
console.log("running~")
}
}
}
function mixinRunner(BaseClass) {
return class extends BaseClass {
flying() {
console.log("flying~")
}
}
}
class Bird {
eating() {
console.log("eating~")
}
}
// var NewBird = mixinRunner(mixinAnimal(Bird))
class NewBird extends mixinRunner(mixinAnimal(Bird)) {
}
var bird = new NewBird()
bird.flying()//flying~
bird.running()//running~
bird.eating()//eating~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
- 应用:在react中的高阶组件
# 2、JavaScript中的多态
面向对象的三大特性:封装、继承、多态。
- 前面两个我们都已经详细解析过了,接下来我们讨论一下JavaScript的多态。
JavaScript有多态吗?
- 维基百科对多态的定义:多态(英语:polymorphism)指为不同数据类型的实体提供统一的接口,或使用一个单一的符号来表示多个不同的类型。
- 非常的抽象,个人的总结:不同的数据类型进行同一个操作,表现出不同的行为,就是多态的体现。
那么从上面的定义来看,JavaScript是一定存在多态的。
//多态表现一
function sum(m,n) {
console.log(m+n)
}
sum(10,50)
sum('name','kobe')
//多态表现二
function foo() {}
foo()
foo = [1,2]
foo.push(3)
foo = 'abc'
console.log(foo.split('b'))//['a','c']
foo = 3.16
console.log(foo.toFixed(1))//3.2
//...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- java面向对象的多态理解
// 继承是多态的前提
// shape形状
class Shape {
getArea() {}
}
class Rectangle extends Shape {
constructor(width, height) {
super()
this.width = width
this.height = height
}
getArea() {
return this.width * this.height
}
}
class Circle extends Shape {
constructor(radius) {
super()
this.radius = radius
}
getArea() {
return this.radius * this.radius * 3.14
}
}
var rect1 = new Rectangle(100, 200)
var rect2 = new Rectangle(20, 30)
var c1 = new Circle(10)
var c2 = new Circle(15)
// 表现形式就是多态
/*
在严格意义的面向对象语言中, 多态的是存在如下条件的:
1.必须有继承(实现接口)
2.必须有父类引用指向子类对象
*/
function getShapeArea(shape) {
console.log(shape.getArea())
}
getShapeArea(rect1)
getShapeArea(c1)
var obj = {
getArea: function() {
return 10000
}
}
getShapeArea(obj)
getShapeArea(123)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# 3、babel工具
- babel官网 (opens new window)
- 在线ES6转成ES5代码 (opens new window)
- 来看看ES6实现继承的代码转成ES5代码是如何的:
// 1.ES6代码
class Person {
constructor(name,age){
this.name = name,
this.age = age
}
running(){
console.log(this.name,'running')
}
static flying() {
console.log(this.name,'flying')
}
}
class Student extends Person {
constructor(name,age,height){
super(name,age)
this.height = height
}
}
var stu = new Student('lyk',19,1.76)
console.log(stu)
// 2.转成后的ES5代码
"use strict";
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () { }));
return true;
} catch (e) {
return false;
}
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
var Person = /*#__PURE__*/function () {
function Person(name, age) {
_classCallCheck(this, Person);
this.name = name, this.age = age;
}
_createClass(Person, [{
key: "running",
value: function running() {
console.log(this.name, 'running');
}
}], [{
key: "flying",
value: function flying() {
console.log(this.name, 'flying');
}
}]);
return Person;
}();
var Student = /*#__PURE__*/function (_Person) {
_inherits(Student, _Person);
var _super = _createSuper(Student);
function Student(name, age, height) {
var _this;
_classCallCheck(this, Student);
_this = _super.call(this, name, age);
_this.height = height;
return _this;
}
return _createClass(Student);
}(Person);
var stu = new Student('lyk', 19, 1.76);
console.log(stu);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# 4、字面量的增强写法
- ES6中对 对象字面量 进行了增强,称之为 Enhanced object literals(增强对象字面量)。
- 字面量的增强主要包括下面几部分:
- 属性的简写:PropertyShorthand
- 方法的简写:MethodShorthand
- 计算属性名:ComputedProperty Names
var name = "kobe"
var age = 28
var key = "address" + " city"
var obj = {
// 1.属性的增强写法
name: name,//之前写法
age,//增强写法
// 2.方法的增强写法
running: function () {//之前写法
console.log(this)
},
swimming() {//增强写法
console.log(this)
},
eating: () => {
console.log(this)
},
// 3.计算属性名写法
[key]: "广州",// 相当于: 'address city':'广州市'
[name + 123]: 'hahaha'
}
obj.running()
obj.swimming()
obj.eating()
function foo() {
var message = "Hello World"
var info = "my name is kobe"
return { message, info }//属性的增强写法
}
var result = foo()
console.log(result.message, result.info)
console.log(obj)/*{
name: 'kobe',
age: 28,
running: [Function: running],
swimming: [Function: swimming],
eating: [Function: eating],
'address city': '广州'
}*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# 5、解构赋值
# 5.1.解构Destructuring
- ES6中新增了一个从数组或对象中方便获取数据的方法,称之为解构Destructuring。
- 解构赋值 是一种特殊的语法,它使我们可以将数组或对象“拆包”至一系列变量中。
- 我们可以划分为:数组的解构和对象的解构。
# 5.2.数组的解构
- 基本解构过程
- 顺序解构
- 解构出数组:…语法
- 默认值
var names = ["abc", "cba", undefined, "nba", null]
// 之前获取数组中每一项很麻烦,如下:
// var name1 = names[0]
// var name2 = names[1]
// var name3 = names[2]
//1.数组的解构
// 1.1. 基本使用
var [name1, name2, name3] = names
console.log(name1, name2, name3)//abc cba undefined
// 1.2. 顺序问题: 严格的顺序(严格按照顺序进行解构)
var [name11, , , name33] = names
console.log(name11, name33)//abc nba
// 1.3. 解构出数组
var [name111, name222, ...newNames] = names
console.log(name111, name222, newNames)//abc cba [ undefined, 'nba', null ]
// 1.4. 解构的默认值,注意:当数组中的元素 没有定义或者值为undefined的时候,才会使用我们设置的默认值
var [name1111, name2222, name3333 = "default", , name5555 = '我是默认值',name6666='默认值'] = names
console.log(name1111, name2222, name3333, name5555,name6666)//abc cba default null 默认值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 5.3.对象的解构
- 基本解构过程
- 任意顺序
- 重命名
- 默认值
- 对象的剩余内容用法
var obj = { name: "kobe", age: 28, height: 1.98 }
// 之前想获取obj中的key对应的value值很麻烦,如下:
// var name = obj.name
// var age = obj.age
// var height = obj.height
//1.对象的解构
// 1.1. 基本使用
var { name, age, height } = obj
console.log(name, age, height)//kobe 28 1.98
var { age } = obj
console.log(age)//28
e
// 1.2. 顺序问题: 对象的解构是没有顺序, 根据key解构
var { height, name, age } = obj
console.log(name, age, height)//kobe 28 1.98
// 1.3. 对变量进行重命名
var { height: wHeight, name: wName, age: wAge } = obj
console.log(wName, wAge, wHeight)//kobe 28 1.98
// 1.4. 默认值
var {
height: wHeight,
name: wName,
age: wAge,
address: wAddress = "洛杉矶"
} = obj
console.log(wName, wAge, wHeight, wAddress)//kobe 28 1.98 洛杉矶
// 1.5. 对象的剩余内容
var {
name,
age,
...newObj
} = obj
console.log(newObj)//{ height: 1.98 }
// 应用: 在函数中(其他类似的地方)
function getPosition({ x, y }) {
console.log(x, y)
}
getPosition({ x: 10, y: 20 })//10 20
getPosition({ x: 25, y: 35 })//25 35
function foo(num) {}
foo(123)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# 5.4.解构的应用场景
- 解构目前在开发中使用是非常多的:
- 比如在开发中拿到一个变量时,自动对其进行解构使用;
- 比如对函数的参数进行解构;