码迷,mamicode.com
首页 > 其他好文 > 详细

ES6之class

时间:2017-07-04 22:01:42      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:end   his   存在   struct   es6   定义   parent   构造方法   return   

ES5中通常通过构造函数和原型的组合形式来创建对象。在ES6中引入class作为对象模板,

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);

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

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

Class继承

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

 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区别:

(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

                       技术分享

 

ES6之class

标签:end   his   存在   struct   es6   定义   parent   构造方法   return   

原文地址:http://www.cnblogs.com/microcosm/p/7118356.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!