一、概念:js中类是对某一类事务的抽象,我们可以通过类new出具体的实例对象,比如手机是一个抽象的类,而我们自己用的手机就是一个具体的对象
es6中引入了类的概念 class 里面有自己的构造器和方法
如下代码
class Person {
constructor() {
}
fn() {
console.log('我是类')
}
}
let man =new Person()
这里person是一个类 而man是类new的一个实例
constructor是类内部的一个构造器,当我们new一个对象实例时就会自动调用constructor这个函数(相当于ES5中构造函数内部隐式生成的this对象,并把它return到外部)
类中的函数要注意几点:
1.没有function 关键字 2.函数之间不需要逗号隔开
二、类的继承
class Father {
constructor(money) {
this.money = money
}
say() {
console.log('father say')
}
}
class Son extends Father {//extends关键字 继承父类
constructor(sons) {
super(sons)//super关键字 把子类的参数传给父类
}
say() {
super.say()//子类里调用父类say方法
console.log('son say something')
}
}
let son = new Son(500)
son.say() //father say son say something 方法调
//用遵循就近原则 子类有的方法会优先调用自身的,没有就会调用父类的
console.log(son.money) //500
注意 es6中类不存在变量提升 类先new后声明会报错 类里面的公用属性和方法调用要加this(表示是当前这个实例对象调用得)否则报错
class Car{
constructor(){
//new的时候 隐式创建 this对象
this.name=name;
this.color=color
//并把this return到外部
}
run(){
console.log(this.name)//调用公共属性 加this
}
}
let car=new Car('baoma','red')//new 时自动调用 constructor函数
//并且把this指向car这个类
类里的this指向 constructor里面的this指向实例对象 类里的构造函数this指向调用者,即谁调用就指向谁
<button class="btn">click</button>
<script>
let btn = document.getElementsByClassName('btn')[0]
let that//声明全局变量 that
class Car {
constructor(name, color) {
this.name = name;
this.color = color;
that = this //将constructor里面的this保存到全局变量that中
}
run() {
console.log(this.name)
console.log(this.name + 'running')
console.log(this)//指向调用者 car
}
sayname() {
console.log('i am baoma')
console.log(this.name)//调用者是btn btn里没有name 打印为空
console.log(that.name)//that保存了constructor里面的this所以这里打印出 baoma
}
}
let car = new Car('baoma', 'red')
car.run()//实例对象调用run方法
btn.onclick = that.sayname//btn调用sayname
console.log(that === car)//true 说明constructor里面的this指向实例car
</script>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。