ES6 class
class本质不过是一个语法糖,其底层还是通过 构造函数 去创建的函数。包含constructor
、属性、方法等。
// 类
class Studet {
constructor(name, age) {
//this 指向的是当前这个构造函数的对象/实例
console.log(this);
//属性
this.name = name
this.age = age
}
//方法
say() {
console.log(`姓名${this.name},年龄${this.age}`);
}
}
//通过类new 对象/实例
new Studet("zhangsan", 20)
ES6 class继承 class继承包含extend和super,扩展属性方法
// 父类
class People {
constructor(name, age) {
//this 指向的是当前这个构造函数的对象/实例
console.log(this);
//属性
this.name = name
}
//方法
eat() {
console.log(`姓名${this.name}吃饭`);
}
}
// 子类
class Studet extends People {
constructor(name, age) {
super(name)
this.age = age
}
say() {
console.log(`姓名${this.name},年龄${this.age}`);
}
}
// 子类
class Teacher extends People {
constructor(name, major) {
super(name)
this.major = major
}
teach() {
console.log(`姓名${this.name}教课${this.major}`);
}
}
//通过类new 对象/实例
const zhangsan = new Studet("zhangsan", 20)
zhangsan.eat()
zhangsan.say()
const lisi = new Teacher("lisi", "语文")
lisi.teach()
lisi.say()//报错,没有这个方法
重点:
lisi instanceof Teacher //true
lisi instanceof People //true
lisi instanceof Object //true
原型
- 每个class都有显性原型prototype
- 每个实例都有隐性原型__protp__
- 实例的__protp__指向class的prototype
//隐形原型
lisi.__protp__ //People
//显示原型
Teacher.prototype //People
//lisi的显示原型等于Teacher的显示隐形原型
lisi.__protp__ ===Teacher.prototype //true
原型链
图出自网络,侵权删
Teacher.prototype.__protp__ ===People.prototype //true
Studet.prototype.__protp__ ===People.prototype //true