1 <script>
2 // es5的语法实现
3 function Person1(name, age) {
4 this.name = name;
5 this.age = age;
6 }
7
8 Person1.prototype.run = function () {
9 console.log('running')
10 }
11 console.log(Person1)
12 // 输出结果,直接返回函数定义
13 /*ƒ Person1(name,age){
14 this.name =name;
15 this.age =age;
16 }*/
17
18 console.log(Person1.prototype);
19 // 输出结果,返回函数prototype指向的函数原型对象。
20 // (每个函数被解析时,解析器都会隐式添加一个prototype属性,指向函数原型对象,该对象初始内容只包含一个键值对: constructor: f () ,后续通过构造函数的prototype属性添加的内容,将会以键值对的形式出现在该对象中)
21 /*{constructor: ƒ}*/
22
23 const p1 = new Person1('张三', 20)
24 console.log(p1)
25 // 输出结果,返回一个实例对象,包含的键值对内容就是构造函数中含有的,该实例对象有一个隐式__proto__属性,指向Person1.prototype
26 /*Person1 {name: '张三', age: 20}*/
27
28 p1.run()
29 // 输出结果running,实例对象本身是没有run方法的,实例对象是按照构造函数模板来实例化的,能访问到该方法是因为存在原型链
30 /*running*/
31
32 // es6语法实现
33 class Person2 {
34 }
35
36 console.log((typeof Person2)); //function,本质还是一个函数
37
38 console.log(Person2)
39 // 输出结果,返回定义
40 /*class Person2 {
41 }*/
42
43 console.log(Person2.prototype)
44 //输出结果,说明两个事情,第一,prototype属性仍然存在,第二,即使类中没有定义constructor方法,原型默认有一个键值对,且key的value值指向类定义
45 /*{constructor: ƒ}*/
46
47 class Person3 {
48 name;
49 age;
50 }
51
52 console.log(Person3)
53 // 输出结果,返回定义
54 /*class Person3 {
55 name;
56 age;
57 }*/
58
59 class Person4 {
60 //定义在类顶部的属性,是实例属性,但注意不要加this
61 score = 90;
62
63 //class中所有的方法都是添加在原型链上面的
64 constructor(name, age) {
65 //constructor中的this紧跟的变量也为实例属性,不在原型链上
66 this.sex = 'male';
67 this.name = name;
68 this.age = age
69 }
70
71 swim() {
72 console.log('swimming')
73 }
74
75 //由于添加了static关键字,该方法(属性名同理)不会出现在实例中,也不会出现在原型链上。只能通过类名.方法名调用;如果该方法中存在this,this指向该类,即this等价与Person4,不是指向实例对象
76 static log() {
77 console.log('我是静态的')
78 }
79 }
80
81 console.log(Person4) //返回class Person4的定义
82 const p4 = new Person4('zhangsan', 20) //score是实例属性,swim()是原型链上面的方法,即等价与Person4.prototype.swim=function(){},new的过程就是调用constructor方法
83 console.log(p4)
84 // 输出结果,包含实例属性和constructor中涉及的内容
85 /* Person4 {score: 90, name: 'zhangsan', age: 20}*/
86
87 // 注意。Person4的prototype属性仍然存在,且有该关系:Person4 === Person4.prototype.constructor 它们值输出就是类的定义
88 console.log(Person4.prototype)
89 // 输出结果,包含且仅包含class中定义的所有方法,因为class中定义的所有方法都是定义在原型链上,即Person4.prototype上
90 /*{constructor: ƒ, swim: ƒ}*/
91
92 </script>