目录
class类
使用class这个关键词定义一个类,基于这个类创建实例以后会自动执行constructor方法,此方法可以用来初始化
1、声明类
class 类名{ }
//1。声明类
class Student {
constructor(name, age) {
//对象初始化
this.name = name
this.age = age
this.subjects = []
}
set subject(subject) {
this.subjects.push(subject)
}
get subject() {
return this.subjects
}
//方法将来定义在原型上
study() {
console.log('hello world')
}
}
2、实例化对象
new 类() ---->默认会执行类中的constructor方法
//2、实例化对象 new 类()--->默认会执行类中的constructor方法
const s1 = new Student('zs', 12)
console.log(s1.__proto__)//{constructor: ƒ, study: ƒ}
s1.study()
const s2 = new Student('ls', 22)
// s2.subjects.push('chinese')
// console.log(s2.subjects)//['chinese']
s1.subject = 'chinese'
console.log(s1.subject)//['chinese']
console.log(s2)//Student {name: 'ls', age: 22, subjects: Array(0)}
console.log(s1.study === s2.study)//true
3、get和set
get可以用来得获取属性,set可以去设置属性
class Person {
constructor() {
this.hobbies = [];
}
//设置属性
set hobby(hobby) {
this.hobbies.push(hobby);
}
//获取属性
get hobby() {
return this.hobbies;
}
}
let person = new Person();
person.hobby = 'basketball ';
person.hobby = 'football ';
console.log(person.hobby);
4、静态方法
静态方法有两种形式:
一种是:类名.静态属性或方法 = 值
另一种是:在类里面添加静态的方法可以使用static这个关键词,静态方法就是不需要实例化类就能使用的方法
静态方法里的this是类本身
// 1 声明类
class Student {
constructor(name, age) {
// 对象初始化
this.name = name
this.age = age
this.subjects = []
}
// 方法将来定义在原型上
study() {
console.log(this)
console.log('good good study')
}
// 2 通过static定义静态方法
static eat() {
console.log(this) // 类本身
console.log('eating')
}
}
// 静态方法 1 类名.静态属性或方法 = 值
// Student.eat = function () {
// console.log('eating')
// }
// 2 实例化对象 new 类() -> 默认会执行类中的constructor方法
const s1 = new Student('zs', 18)
Student.eat()
s1.study()
5、继承extends
super()调用父类的构造函数
super()相当于父类的实例,原型上的方法
子类定义方法想要父类的方法通过 super.父类的方法()
父类用箭头函数另写的方法是实例方法
//父类
class Father{
money=10000000//实例属性
//实例方法
say=()=>{
console.log('saying')
}
constructor(school){
this.car='audi'
this.school=school
}
//原型方法
manager(){
console.log('中西管理')
}
}
//子类
class Son extends Father{
constructor(){
//必须先调用父类的构造函数
super('哈佛')//调用父类的构造函数
}
manager(){
//super 相当于父实例
super.manager()
console.log('孙子兵法管理模式')
}
}
const s1=new Son()
const s2=new Son()
console.log(s1.say===s2.say)//false
console.log(s1.money)//10000000
console.log(s1.car)//audi
console.log(s1.school)//哈佛
s1.manager()
new出来的实例对象,调用父类的实例方法是不相等的