JavaScript-原型和原型链

2020/7/4 JavaScript

# 原型和原型链图示

原型和原型链

# 原型和原型链图示

原型和原型链

// 简介
1. 每个构造函数中有 prototype 属性(构造函数和普通函数不同),对应的就是原型
2. 每个实例对象除了 null 之外都具有一个 __proto__ 属性,这个属性指向该对象的原型
3. 每个原型都有一个 constructor 属性指向关联的构造函数
----------------------------------------------------------------------------------------------
// 面向对象和继承
1. es5
function user(name, pass) {
  this.name = name
  this.pass = pass
  // 方法不可写在函数内部, 如果写在函数内部而不是原型链上的话会导致每个实例都会有这个方法
  // 并且实例修改了方法不会影响到另一个实例的eat方法, 和放在原型链上的方法一样属于实例方法
  this.eat = function() {
    console.log('eat')
  }
}
// 静态方法
User.walk = function() { console.log('walk') }
// 方法放在原型上添加
User.prototype.showName = function() { console.log(this.name) }
User.prototype.showPass = function() { console.log(this.pass) }
// 继承,构造函数继承 + 原型链继承 = 组合继承
function vipUser(name, pass, level) {
  user.call(this, name, pass) // 继承属性,构造函数继承
  this.level = level
}
// 继承方法
方法1: vipUser.prototype = Object.create(user.prototype) // 原型链继承
方法2: vipUser.prototype = new user()
       vipUser.prototype.construtor = vipUser
// 自己的方法
vipUser.prototype.showLevel = function() { console.log(this.level) }
----------------------------------------------------------------------------------------------
2. es6
class user {
  constructor(name, pass) {
    this.name = name
    this.pass = pass
    // 方法直接放在内部
    showName() { console.log(this.name) }
    showPass() { console.log(this.pass) }
  }
}
// 继承
class vipUser extends User { // 子类可以通过 this 访问父类的属性和方法和 ts 不同, 在 js 中没有私有属性的概念
  constructor(name, pass, level) { // 如果子类的构造函数是空的可以省略不写包括 super
    super(name, pass) // 相当于call继承属性,方法自动继承
    this.level = level
    showLevel() { console.log(this.level) }
  }
}
----------------------------------------------------------------------------------------------
// es6
1. 只读属性(保护),要写在construtor的下面
   get 名称() {}
   set 名称() {} //名称是类上的属性而不是方法,名称不是属性名称而是对外访问的出入口
2. 静态方法指的是类方法,构造函数除外
3. 实例方法指的是写在构造函数内的方法
4. es5的实例方法就是在原型上的方法和写在类中的this.方法名
5. 静态方法则是在构造函数外且不是原型上的方法,如类名.方法名 // User.walk = function() { console.log('walk') }
6. es6静态方法是在class中的方法前面加上static,不加则是实例方法, 使用时也是通过类名.方法名访问
7. 继承extendssuper,如果子类没有直接的构造属性,constructor和super可以省,如果有自己的属性则不能省
----------------------------------------------------------------------------------------------
// 其他
1. 插件机制: 相当于给prototype上增加新的函数
2. 扩展机制: 继承
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
Last Updated: 2024/6/11 14:20:38
    飘向北方
    那吾克热-NW,尤长靖