1 //#region ES5和ES6类对象的声明对比
2 //ES5类对象的写法是
3 // function Phone(brand, price) {
4 // this.brand = brand
5 // this.price = price
6 // }
7 // 给Phone添加一个方法 callMethod()
8 // Phone.prototype.callMethod=function(){
9 // console.log(this.brand+':'+this.price);
10 // }
11
12 // 实例化对象并调用方法
13 // let huawei=new Phone('华为','4999')
14 // huawei.callMethod()
15
16 //ES6新增了class类的写法
17 // class mPhone{
18 // 构造方法,名字固定
19 // constructor(mbrand,mprice){
20 // this.mbrand=mbrand
21 // this.mprice=mprice
22 // }
23 //
24 // mCallMethod(){
25 // console.log('class类中的方法')
26 // }
27 // }
28
29 // let mphone=new mPhone('huawei','5000')
30 // mphone.mCallMethod() // 输出:class类中的方法
31 //#endregion
32
33 // ES5类对象的继承
34 // function Phone(brand, price) {
35 // this.brand = brand;
36 // this.price = price;
37 // }
38
39 // Phone.prototype.call = function () {
40 // console.log('打电话');
41 // }
42
43 // function SmartPhone(brand, price, color) {
44 // Phone.call(this, brand, price) // 利用call方法将Phone对象指向SmartPhone的实例对象,从而初始化SmartPhone实例对象的值
45 // this.color = color
46 // }
47
48 // 设置子级构造函数的原型
49 // SmartPhone.prototype=new Phone;// 继承Phone的方法
50
51 // SmartPhone.prototype.playGame = function () {
52 // console.log('打游戏');
53 // }
54
55 // let xiaomi = new SmartPhone('小米', '1999', '5.5inch')
56 // console.log(xiaomi);
57
58 // ES6类的继承
59 class Phone {
60 // 注意class中的构造方法不是必须的,如果没有也可以
61 constructor(brand, price) {
62 this.brand = brand;
63 this.price = price
64 }
65
66 call() {
67 console.log('打电话!!');
68 }
69 }
70
71 // extends 关键字表示继承自哪个类
72 class SmartPhone extends Phone {
73 // 构造方法
74 constructor(brand, price, color) {
75 // 调用父类的构造方法传参
76 super(brand, price) // super指代父类的构造方法constructor
77 this.color = color
78 }
79
80 playGame() {
81 console.log('打游戏!!!');
82 }
83
84 // 定义一个与父类的同名方法实现对父类方法的重写(注:子类中不能调用父类的方法)
85 // call(){
86 // console.log('打视频电话!');
87 // }
88 }
89
90 let chuizi = new SmartPhone('锤子', '2999', '黑色')
91 chuizi.call() // 打电话!!