ES6 中新增了 class 特性 https://developer.mozilla.org/zh-CN/docs/web/JavaScript/Reference/Classes 可以让我们更加方便的使用'类'的概念, 用以替代之前的 function.prototype 相关的操作.
新增概念大约如下:
- constructor
- super
- extends
- static
ES6 的 class 功能其实是 prototype 的语法糖, 把原型链相关的写法变成了上面的 5 中操作符写法. 本质上这个 class 仍然是个构造函数; 到 ES6 的发展阶段, js 的数据类型也只增加了一个 symbol(基本类型), 其他的仍然没有改变.
构造函数
- // 原型方式实现
- function People(name,age){
- this.name = name
- this.age = age
- }
- People.prototype.eat = function(){
- console.log(this.name + 'eat')
- }
- let person = new People('jack',20)
- person.eat() //jack eat
使用 class 的方式来实现即:
构造函数 constructor 是用于创建和初始化类中创建的一个对象的一种特殊方法
在一个类中只能有一个名为 "constructor" 的特殊方法
- class People {
- constructor(name,age){
- this.name = name
- this.age = age
- }
- eat(){
- console.log(this.name + 'eat')
- }
- }
- let person = new People('jack',20)
- person.eat()
上面是一个简单的构造函数的两种写法, 涉及到了 constructor 的使用, 简单来说, constructor 指的就是构造函数的自有属性.
涉及到继承
extends 关键字用于类声明 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/class 或者类表达式 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/class 中, 以创建一个类, 该类是另一个类的子类.
- class People {
- constructor(name,age){
- this.name = name
- this.age = age
- }
- eat(){
- console.log(this.name + 'eat')
- }
- }
- //man 继承 people
- class man extends People {
- constructor(name,age,sex,height){
- super(name,age)
- this.sex = sex
- this.height = height
- }
- run(){console.log(this.name + 'is run and he is' + this.age + 'years old')}
- status(){console.log(this.name + 'is' + this.height)}
- }
- let sam = new man('sam',20,man,180)
- sam.eat() //sam eat
- sam.status() //sam is 180
- sam.run() //sam is run and he is 20 years old
chrome 控制台打印的结果
静态方法 static
静态方法调用直接在类上进行, 不能在类的实例上调用. 静态方法通常用于创建实用程序函数; 静态方法不能直接在非静态方法中使用 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this 关键字来访问 参考文档 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes/static
- class parent {
- static speak(){
- console.log(this)
- }
- eat(){
- console.log(this)
- }
- }
- let human = new parent()
- human.eat() // 返回 parent 这个 class
- human.speak() // 这样写是错误的
正确查看静态方法写法应该为:
- let obj = parent.speak
- obj() //undifined
static 方法
首先: 如果一个属性是函数, 那么我们就叫这个属性为方法
从上面我们可以看得出来, 简单理解就是:
extends 操作符是代替了 Object.create()实现了继承的功能;
constructor 操作符事实上可以理解成 Object 原型链上的一个方法 (函数) 用来实现在一个 class 自有属性;
super 操作符也可以认为是 Object 原型链上的一个方法, 用来实现子类自有属性的一种方法, 在上面继承代码块的部分就使用了 super 操作符;
class 去除了全部涉及到 prototype 的写法, 但是基于 prototype 去理解这种写法还是很容易的
来源: http://www.jianshu.com/p/3e93d1bdc234