ES6之class

ES5中一般经过构造函数和原型的组合形式来建立对象。在ES6中引入class做为对象模板,app

Class定义语法

class point{
     constructor(x,y){
               this.x = x;

               this.y = y;
     }

     toString(){
               return '[' + this.x + ',' + this.y + "]" ;
     }
   }

var instance = new point(1,2);

等价于函数

function point(x, y){
       this.x = x;
       this.y = y;
   }
   point.prototype.toString = function(){
        return '[' + this.x + ',' + this.y + "]" ;
   }

var instance = new point(1,2);this

在class中constructor方法就是构造方法,this关键字表明实例对象,toString方法其实是protoType上的方法,方法的定义不须要加关键字,而且方法之间不能用逗号分隔。spa

注意:ES6的class中不存在变量提高,这与继承有关,必须保证子类在父类定之后使用。class内部默认就是严格模式。prototype

Class继承

ES5中使用原型,让一个引用类型继承另外一个引用类型的属性和方法。code

 class child extends point{
     constructor(x,y,z){

               supor(x,y);

               this.color = z;
     }

     childMethod(){
               console.log(this.z);
     }

   }

经过extends关键字实现继承,在子类的constructor构造函数中调用super方法,继承父类的this。同时能够添加本身的实例属性z和原型函数childMethod。对象

与ES5区别:blog

(1)在ES5中是先建立 子类的this对对象,而后将父类的方法添加到this上,即Parent.apply(this)。而ES6中是用super方法建立父类的实例对象this,再用子类的构造函数修改this。所以在子类中必须调用super方法后才可使用this。继承

(2)ES5中,每一个对象都有_proto_属性,指向对应构造函数的原型对象;而prototype指向其方法的原型对象。原型链

ES6中

l  子类的_proto_属性表示构造函数的继承,老是指向父类。

l  子类的prototype属性的_proto_属性表示方法的继承,老是指向父类的prototype属性。

l  子类的_proto_属性的_proto_属性,指向父类实例的_proto_属性。

在ES6中,使用class类实现继承,与ES5原型链继承相同的是,而子类prototype(原型对象)的__proto__属性老是指向父类的prototype(原型对象)属性,即child.prototype.__protot__ = parent.prototype。与ES5原型链继承不一样的是,子类的__proto__老是指向父类,即child.__proto__ = parent(注意:ES5中,child.__proto__ = Function.prototype),表示构造函数的继承。并且子类__proto__的__proto__是父类的__proto__,也就是说,子类原型的原型是父类的原型。

class parent{

          constructor(x,y){

                   this.x = x;

                   this.y = y;

          }

          toString(){

                   return '[' + this.x + ',' + this.y + "]" ;

          }

   }

//class 继承

   class child extends parent{
          constructor(x,y,z){
                   supor(x,y); //super()建立父类的实例
         }
          childMethod(){
                   console.log(this.z);
          }

   }

   console.log(child.__proto__ == parent); //true
   console.log(child.prototype.__proto__ == parent.prototype); //false

                       

相关文章
相关标签/搜索