这里结合class 理解
// 父类
class People {
constructor(name) {
this.name = name
}
eat() {
console.log(`${this.name} eat something`)
}
}
// 子类
class Student extends People {
constructor(name, number) {
super(name)
this.number = number
}
sayHi() {
console.log(`姓名 ${this.name} 学号 ${this.number}`)
}
}
// 实例
const xialuo = new Student('夏洛', 100)
console.log(xialuo.name)
console.log(xialuo.number)
xialuo.sayHi()
xialuo.eat()
class实际上是函数,可见还是语法糖。typeof 类为 ‘function’。
- 原型关系:
每个
class都有显示原型prototype,每个实例都有隐式原型__proto__,实例的__proto__指向对应class的prototype。 - 基于原型的执行规则: 获取属性或者执行方法时,先在自身属性和方法查找,如果找不到则自动去__proto__中查找。
- 原型链:
顺着隐式原型
__proto__查找原型对象,Object.prototype__proto__为null,终止原型链。 instanceof原理 (判断一个实例是否属于某种类型): instanceof 本质在原型链上通过__proto__隐式原型向上查找是否有对应的类的显式原型,查得到就为true,否则为false。
- hasOwnProperty hasOwnProperty表示是否有自己的属性。这个方法会查找一个对象是否有某个属性,但是不会去查找它的原型链