ES6中的类

 

ES6提供了更接近传统语言的写法,引入了class(类)这个概念,通过class关键字,可以定义类。

            //es6中声明一个类的方法,使用class关键字
            class Car{
                //构造函数的固定写法,类似于函数的简洁表示法const obj ={ a(){}  }
                constructor(...args){  //通过剩余参数...将实例中传进来的所有参数作为一个数组放进args中
                    console.log('开始造车')
                    console.log(args);   // 打印结果为 ['蓝色',3]
                }
            }
            
            //类的实例化
            new Car('蓝色',3);
            
            

 

 

 

 

            class Vehicle{
                constructor(wheel,color,length,width){
                    this.wheel =wheel;  //this指向实例化对象v
                    this.color = color;
                    this.length = length;
                    this.width = width;
                    
                    this.speed = 0;
                    
                }
                //方法
                speedUp(){
                    this.speed += 1;
                }
                
                
                
            }
            const v = new Vehicle(3,'#f00',20,40);
            
            
            console.log(v.color);
            console.log(v.speed)  //0
            
            v.speedUp();
            console.log(v.speed);  //1
            console.log(v);  
            

 

posted @ 2020-09-12 00:21  是桂  阅读(337)  评论(0编辑  收藏  举报