类语法是ES6中新增的一个亮点特性,下文简单对类的使用进行简要说明(仅做为我的层面的理解)函数
在JavaScript中,实例化一个对象的传统使用方法是经过构造函数。
以下示例:this
function Count(num1,num2){ this.num1 = num1; this.num2 = num2; } //构造函数 Count.prototype.number = function(){ console.log(this.num1,this.num2); } //实例化对象 var count = new Count(1,2); count.number(1,3);
ES6引入了Class
(类)这一律念,能够经过class
关键字,定义类。
以下示例:prototype
//定义类 class Count{ //构造方法 constructor(x,y){ //this表示实例对象 this.x = x; this.y = y; } //非静态方法,能够直接用实例.方法名来访问 sum(x,y){ let sum = x+y; console.log('sum is :',sum) } //静态方法,须要经过构造器或者类才能访问的到 static sub(x,y){ let sub = x - y; console.log('sub is :',sub); } } var count = new Count(); //非静态方法,能够直接访问 count.sum(1,2); // sum is :3 //静态方法: //(1)实例对象.constructor.方法名 count.constructor.sub(5,1); // sub is :4 //(2)类名.方法名 Count.sub(5,1); // sub is :4 count.hasOwnProperty('x'); // 定义在this上,是实例对象自身的属性true count.hasOwnProperty('y'); // true count.hasOwnProperty('sum'); // 定义在原型对象上,false count._proto_.hasOwnProperty('sum'); // true
经过以上的小实例,总结下面几点:code
function
关键字。constructor
方法,若没有显示定义,则一个空的会被添加。static
关键字声明的方法,须要经过构造函数constructor
或者使用类名才能够访问的到。this
对象上,不然都是定义在原型上(即class
上)。其实,ES6的类,能够看做是构造函数的另一种写法。<br/>对象
class B{} var b = new B(); typeof B; //`function` typeof B === B.prototype.constructor //true typeof b.constructor === B.prototype.constructor //true
对比ES6和ES5,有如下相同点继承
再来看ES6与ES5的不一样点ip
因为类的方法都定义在prototype上面,那么咱们可使用Object.assign方法给类一次添加多个方法。prototype的constructor方法,直接指向“类”自己,这和ES5的行为是有区别的。另外,类内部全部定义的方法,都是不可枚举的,而ES5中,prototype上的方法都是可枚举的。
示例以下:
//ES5 function Test(){} Test.prototype.log = function(){} var test = new Test(); Object.keys(Test.prototype); //列举出给定对象自身可枚举属性(不包括原型上的属性) //['log'] Object.getOwnPropertyNames(Test.prototype); //列举出给定对象全部自身属性的名称(包括不可枚举属性但不包括Symbol值做为名称的属性) //['prototype','log'] //ES6 class Test2{ toValue(){} } var test2 = new Test2(); Object.keys(Test2.prototype); //[] Object.getOwnPropertyNames(Test2.prototype); //['constructor','toValue'];
类中所定义的方法,都会被实例继承,若是在一个方法前,加上
static
关键字,那该静态方法不会被实例继承,而是直接经过类来调用的。
class Foo{ static addMethod(){ console.log(this); console.log('hello class'); this. } } //直接经过类来调用 Foo.addMethod(); //Foo , hello class //实例不会继承静态方法,因此调用会报错 var foo = new Foo(); foo.addMethod(); //TypeError:foo.addMethod is not a function
注意:get
static
静态方法包含this
关键字,这个this
指的是类,而不是实例。super
对象上调用。待续……原型