类:抽取了对象的公共部分,泛指某一大类(class)
对象特指某一个,通过类实例化一个具体的对象
面向对象的思维特点
1.抽取(抽象)对象共用的属性和行为组织(封装)成一个类(模版)
2.对类进行实例化,获取类的对象
类和对象的使用
<script>
// 创建一个类,泛指某一大类
class Father {
constructor(uname,age) { //constructor定义构造函数,传参
this.uname = uname
this.age = age
}
}
// 利用类创建对象
let son = new Father('lisi',18)
let zs = new Father('zhangsan',18)
console.log(son);
console.log(zs);
</script>
类名习惯性首字母大写
类里的constructor函数,可以接受传递过来的参数,同时返回实例
在class可设置一些公共的方法
class Father {
constructor(uname,age) {
this.uname = uname
this.age = age
}
say() {
console.log( '我' + this.uname +'是法外狂徒');
// console.log(this.uname);
}
}
// 利用类创建对象
let son = new Father('lisi',18)
let zs = new Father('zhangsan',18)
console.log(son);
console.log(zs);
son.say()
zs.say()
设置公共类设置方法,不需要逗号隔开,不需要写function
类的继承
<script>
class Father {
constructor(x,y) {
this.x = x
this.y = y
}
computed() {
console.log(this.x + this.y);
}
}
class Son extends Father {
constructor(x,y) {
super(x,y)
}
}
let son = new Son(1,2)
let son1 = new Son(11,22)
// console.log(son);
son.computed()
son1.computed()
</script>
子类构造函数继承父类构造函数要用到super引用父类构造函数里的函数(方法)
继承中的属性或者方法查找原则:就近原则
<script>
class Father {
constructor(x,y) {
this.x = x
this.y = y
}
num() {
console.log(this.x + this.y);
}
}
class Son extends Father {
constructor(x,y) {
super(x,y)
this.x = x
this.y = y
}
decurrent() {
console.log(this.x - this.y);
}
}
let son = new Son(8,2)
son.decurrent()
son.num()
</script>
子类构造函数继承父类方法,同时自身添加一个方法,用super()继承父类函数方法时,必须把super放在this的前面
<script> class Father { constructor(x,y) { this.x = x this.y = y this.btn=document.querySelector('button') this.btn.onclick=this.slove //不能加括号,加括号是直接执行 } slove() { console.log('1111111111111'); } } let son = new Father() // son.slove() </script>
在es6中类没有变量提升,所以必须先定义类,才能通过类实例化
在类里面的共有的属性和方法一定要加this使用