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

ES6中class类用法

时间:2017-12-15 17:23:46      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:war   实现继承   span   www.   script   cto   需要   ret   engine   

之前想要通过javascript来实现类,通常会采用如下构造函数的模式:

 1 function Person(name,age,job){
 2   this.name = name;
 3   this.age = age;
 4   this.job = job;
 5   this.friends = [‘Shelby‘,‘Court‘];
 6 }
 7 Person.prototype = {
 8   constructor:Person,
 9   sayName: function(){
10   document.write(this.name);
11  }
12 }

 

然后通过实例化调用:

1 var person1 = new Person(‘lf‘,23,‘software engineer‘);
2 person1.sayName();

 

下面看看使用ES6的类如何处理:

 1 class Person {
 2  constructor(name, age, job) {
 3   this.name = name;
 4   this.age = age;
 5   this.job = job;
 6   this.friends = [‘Shelby‘,‘Court‘]
 7  }
 8 
 9  sayName () {
10   document.write(this.name);
11  }
12 }

 

可以看到简便了不少。

Class语法的推出可不光光是为了简化噢,还有很多关键字。比如:

static关键字用来定义类的静态方法,静态方法是指那些不需要对类进行实例化,使用类名就可以直接访问的方法。静态方法经常用来作为工具函数:

 1 class Point {
 2   constructor(x, y) {
 3     this.x = x;
 4     this.y = y;
 5   }
 6   static distance(a, b) {
 7     const dx = a.x - b.x;
 8     const dy = a.y - b.y;
 9     return Math.sqrt(dx*dx + dy*dy);
10   }
11 }
12 const p1 = new Point(5, 5);
13 const p2 = new Point(10, 10);
14 console.log(Point.distance(p1, p2));

 

但是需要注意的是,ES6中不能直接定义静态成员变量,但是我们可以通过另外的方式来实现:

1 static get baseUrl() {
2   return ‘www.baidu.com‘
3 }

 

 

在类语法推出之前,我们想要实现继承,必须通过prototype来指定对象,而现在我们可以通过extends关键字来实现继承

 1 class Animal {
 2  constructor(name) {
 3   this.name = name;
 4  }
 5  speak() {
 6   console.log(this.name + ‘ makes a noise.‘);
 7  }
 8 }
 9 class Dog extends Animal {
10  speak() {
11   console.log(this.name + ‘ barks.‘);
12  }
13 }

 

但是需要注意的一点就是,继承的原理还是在利用prototype这点没有变,只不过extends裹了一层语法糖而已。

希望本文所述对大家ECMAScript程序设计有所帮助。

ES6中class类用法

标签:war   实现继承   span   www.   script   cto   需要   ret   engine   

原文地址:http://www.cnblogs.com/lcccc/p/8044010.html

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