class类

ES6提供了更接近传统语言的写法,引入了Class这个概念,作为对象的模板。通过class关键字,可以定义类。

基本上,ES6的class可以看作只是一个语法糖,它的绝大部分功能,ES5都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。

构造函数

在ES5中,我们也可以实现构造函数:

 

 在ES6中,我们实现使用class来实现相同的功能:

 需要注意的是,在class里面,方法必须使用call(){}的这个语法形式,不能使用ES5中对象的完整形式。

 继承

在ES5中使用prototype实现继承

 function Phone(brand,price){
            this.price = price;
            this.brand = brand;
        }
        Phone.prototype.call = function(){
            console.log('我可以打电话');
        }
        function SmartPhone(brand,price,color,size){
            Phone.call(this,brand,price);
            this.color = color;
            this.size = size;
        }
        //设置子级构造函数的原型
        SmartPhone.prototype = new Phone;
        SmartPhone.prototype.constructor = SmartPhone;

        //声明子类的方法
        SmartPhone.prototype.Phone = function(){
            console.log('我可以拍照');
        }
        SmartPhone.prototype.playGame = function(){
            console.log('我可以玩游戏');
        }
        const Huawei = new SmartPhone('华为',4999,'黑色','5.5');
        Huawei.call();
        Huawei.playGame();
        console.log(Huawei);

 在ES6中实现继承就要简便很多

class Phone{
            constructor(brand,price){
                this.price = price;
                this.brand = brand;
            }
            call(){
                console.log('我可以打电话');
            }
        }
        class SmartPhone extends Phone{
            constructor(brand,price,color,size){
               super(brand,price);
                this.color = color;
                this.size = size;
            }
            Phone(){
                console.log('我可以拍照');
            }
            playGame(){
                console.log('我可以玩游戏');
            }

        }
        const Huawei = new SmartPhone('华为',4999,'黑色','5.5');
        Huawei.call();
        Huawei.playGame();
        console.log(Huawei);

 class中的getter和setter方法

 

原文地址:https://www.cnblogs.com/yuyujuan/p/14096011.html