在 ES6 规范中,引入了 class 的概念。使得 JS 开发者终于告别了,直接使用原型对象模仿面向对象中的类和类继承时代。
但是JS 中并没有一个真正的 class 原始类型, class 仅仅只是对原型对象运用语法糖。所以,只有理解如何使用原型对象实现类和类继承,才能真正地用好 class。
本质上js中class其实是构造函数的另一种写法,使之更加直观的展现构造器中的各项属性
基本使用
使用class关键字创建一个类
class test {
constructor(val) { //初始化函数,创建对象时自动调用该方法
this.name = val
}
sayName(){
console.log(this.name)
}
}
let o = new test('小猫')
o.sayName() //小猫
注意点:
(1)constructor是一个构造函数方法,创建对象时自动调用该方法
(2)constructor是类必须的一个属性,少了他类的创建会报错,如果我们不写的话js会给他自动加上
(3)this指的是实例化对象,就相当于构造函数中的this,指向的是当前创建的对象
(4)类中声明函数不需要function关键字,直接函数名即可
(5)方法之间不需要都好分割,加了会报错
因为本质上是构造函数的另一种写法,所以他的使用和一些其他特性都是和构造函数相似的。比如调用都是通过new关键字 并且class也存在prototype这个属性,通过她我们可以给这个类的原型对象定义属性。通过这个类创建出的对象一样会有这个属性
class test {
constructor(val) {
this.name = val
}
sayName(){
console.log(this.name)
}
}
let o = new test('小猫')
test.prototype.getName = function (){
console.log(this.name,'获取到名字啦')
}
o.sayName()//小猫
o.getName()//小猫 获取到名字啦
类的继承
class test {
constructor(val) {
this.name = val
}
sayName(){
console.log('我是基类的sayName')
}
}
class childen extends test{
constructor(name) {
super();
this.name = name
}
sayName() {
console.log('我覆盖了基类的属性')
}
}
let c = new childen('小狗')
c.sayName()//我覆盖了基类的属性
子类继承基类后,同名的属性会覆盖掉基类,以上例子中两个类都有sayName函数,但是调用的时候输出的是子类的sayName。
一个构造函数可以使用 super 关键字来调用一个父类的构造函数。
class test {
constructor(val) {
this.name = val
}
sayName(){
console.log('我是基类的sayName',this.name)
}
}
class childen extends test{
constructor(name) {
super();
this.name = name
}
sayName() {
super.sayName()
// console.log('我覆盖了基类的属性')
}
}
let c = new childen('小狗')
c.sayName()//我是基类的sayName 小狗
同时类也支持get和set操作
class test {
constructor(val) {
this.name = val
this.cs = 1
}
get testget(){
return this.name
}
set testget(val){
console.log('get拦截:'+val)
}
}
let c = new test('小猫')
console.log(c.testget)//小猫
c.testget = '小猪'// get拦截:小猪
网友评论