这是我参与8月更文挑战的第31天,活动详情查看:8月更文挑战
<script>
// 创建一个Person类
class Person{
}
// 创建一个Person的实例对象
const p1 = new Person();
console.log(p1)
</script>
红色的代表实例对象是谁new出来的。蓝色的是实例对象。
为什么他要把,谁缔造的也显示出来呢? 如果还有一个类Dog,我们再打印就可以区分出来。
传递参数
// 创建一个Person的实例对象
const p1 = new Person('tom',18);
接收参数
// 创建一个Person类
class Person{
// 构造器方法
constructor(name,age){
// 构造器中的 this 是谁? ---- 类的实例对象
this.name = name
this.age = age
}
}
构造器中的 this 是谁? ---- 类的实例对象 我们创建两个实例 p1 和 p2, this 就是分别是 p1 和 p2
// 创建一个Person类
class Person{
// 构造器方法
constructor(name,age){
// 构造器中的 this 是谁? ---- 类的实例对象
this.name = name
this.age = age
console.log(this,"this")
}
}
// 创建一个Person的实例对象
const p1 = new Person('tom',18);
const p2 = new Person('bob',19)
可不可以不使用构造器 constructor ?理论上可以不写。
类中写一般方法,什么是一般方法?就是除了构造方法,我们自定义的方法。
// 创建一个Person类
class Person{
// 构造器方法
constructor(name,age){
// 构造器中的 this 是谁? ---- 类的实例对象
this.name = name
this.age = age
// console.log(this,"this")
}
// 一般方法
speak(){
console.log(`我乃${this.name},我今年${this.age}岁`)
}
}
// 创建一个Person的实例对象
const p1 = new Person('tom',18);
const p2 = new Person('bob',19);
// 调用方法
p1.speak()
p2.speak()
仔细看,我们在实例对象中并没有发现这个speak()方法。那speak方法放到了哪里?---类的原型对象上,供实例使用 【Prototype】
再思考一下,speak 的 this 是谁 ?通过实例Person调用speak时,speak中的this就是Person实例。
我们再定义一个类Student,继承自Person类,我们并没有在Student类中写构造器,因为父类Person中已经有构造器了,我们完全可以不写构造器。
<script>
// 创建一个Person类
class Person{
// 构造器方法
constructor(name,age){
// 构造器中的 this 是谁? ---- 类的实例对象
this.name = name
this.age = age
}
// 一般方法
speak(){
console.log(`我乃${this.name},我今年${this.age}岁`)
}
}
// 创建一个类Student继承自Person
class Student extends Person{
}
const s1 = new Student('xiao zhang',15)
console.log(s1)
</script>
那当什么时候我们要写构造器呢? 如果我们想给这个学生类多传一个参数 年级。也就是当Student类和其父类Person传递的参数个数不一致的时候。
// 创建一个类Student继承自Person
class Student extends Person{
constructor(name,age,grade){
this.name = name
this.age = age
this.grade = grade
}
}
const s1 = new Student('xiao zhang',15,"三年级")
报错了,此时需要写 super
class Student extends Person{
constructor(name,age,grade){
// 放在所有之前
super(name,age)
// 只有这个属性是新得到的
this.grade = grade
}
}
那么,此时Student可以调用speak方法吗?
const s1 = new Student('xiao zhang',15,"三年级")
s1.speak()
确实调用了,那么它的speak在哪呢? 按着原型链去找
我想要学生把年级也说出来。那就需要在Student类中再写一个speak方法。也就是重写父类方法
// 创建一个类Student继承自Person
class Student extends Person{
constructor(name,age,grade){
// 放在所有之前
super(name,age)
this.grade = grade
}
speak(){
console.log(`我乃${this.name},我今年${this.age}岁,我读${this.grade}年级`)
}
}
const s1 = new Student('xiao zhang',15,"三年级")
s1.speak()
console.log(s1)
蓝色的是在 Student 的原型上的,而红色的在 Person 的原型上
Student 还想有一个独有的方法 study
study(){
// 通过Student实例调用study时,study中的this就是Student实例
console.log("i like study")
}