ES6中class类用法实例浅析

类语法是ES6中新增的一个亮点特色。我们熟悉的JavaScript终于迎来了真正意义上的类。在之前,想要通过javascript来实现类,通常会采用如下构造函数的模式:

function Person(name,age,job){ this.name = name; this.age = age; this.job = job; this.friends = ['Shelby','Court']; } Person.prototype = { constructor:Person, sayName: function(){ document.write(this.name); } }

然后通过实例化调用:

var person1 = new Person('lf',23,'software engineer'); person1.sayName();

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

class Person { constructor(name, age, job) { this.name = name; this.age = age; this.job = job; this.friends = [‘Shelby','Court'] } sayName () { document.write(this.name); } }

可以看到简便了不少。

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

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

class Point { constructor(x, y) { this.x = x; this.y = y; } static distance(a, b) { const dx = a.x - b.x; const dy = a.y - b.y; return Math.sqrt(dx*dx + dy*dy); } } const p1 = new Point(5, 5); const p2 = new Point(10, 10); console.log(Point.distance(p1, p2));

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

static get baseUrl() { return 'www.baidu.com' }

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

class Animal { constructor(name) { this.name = name; } speak() { console.log(this.name + ' makes a noise.'); } } class Dog extends Animal { speak() { console.log(this.name + ' barks.'); } }

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

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwygyx.html