持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第7天,点击查看活动详情
认识class定义类
我们会发现,按照构造函数形式创建 类,不仅仅和编写普通的函数过于相似,而且代码并不容易理解
在ES6(ECMAScript2015)新的标准中使用了class关键字来直接定义类;
但是类本质上依然是前面所讲的构造函数、原型链的语法糖而已;
如何去使用class去定义一个类呢?
通过声名的形式去定义一个类
class Boy {}
通过表达式的形式去定义一个类
var Boy = class {}
类和构造函数的区别
我们通过打印原型的形式去比较一下class类与构造函数的区别
class Boy {}
var a = new Boy
console.log(Boy.prototype)//{}
console.log(Boy.prototype.__proto__)//[Object: null prototype] {}
console.log(Boy.prototype.constructor)//[class Boy]
console.log(typeof Boy)//function
console.log(p.__proto__ === Boy.prototype)//true
通过打印的结果我们可以发现class类与构造函数的特质其实一致的
这里会有一个疑问 typeof 方法 应该是得class 为什么会出现function呢?
这因为typeof 返回的类型是固定的只有一下的几种类型
number;string;boolean; object; undefined;function
class的构造方法
现在定义一个类,如何才能给类传值呢?
class Boy {}
参考构造函数的方式在boy后再上()?
类中有专门的方法用来接收传递的参数constructor 类的构造方法
class Boy {
constructor(name, age) {
this.name = name
this.age = age
}
}
要注意每个类只有一个构造方法
constructor在执行时做了哪些操作呢?
- 在内存中创建一个对象 例 moni = {}
- 将类的原型prototype赋值给创建出来的对象 例 moni.__ proto __ = Person.prototype
- 将对象赋值给函数的this: new绑定 例 this = moni
- 执行函数体中的代码
- 自动返回创建出来的对象
class中的方法定义
class Boy {
constructor(name, age) {
this.name = name
this.age = age
}
eating() {
console.log(this.name + " eating~")
}
}
创建出来的对象直接进行访问
var p = new Boy()
p.eating()
class中的静态方法
静态方法通常用于定义直接使用类来执行的方法,不需要有类的实例,使用static关键字来定义
class Boy {
constructor(age) {
this.age = age
}
static randomPerson() {
return new Boy(Math.floor(Math.random() * 100))
}
}