JS 中的原型 和 原型链 到底是什么
// 什么是原型 分为 隐式原型 和 显示原型
// 对象和类都有隐式原型的
class Person {
constructor(name) {
this.name = name
}
drink() {
return '喝水'
}
}
// console.log(Person.__proto__.__proto__ === Object.prototype)
class Teacher extends Person {
constructor(name, subject) {
super(name)
this.subject = subject
}
teach() {
return `我是${this.name},交${this.subject}`
}
}
// 由次证明 类也是有隐式原型的 指向的是 父类
console.log(Teacher.__proto__ === Person)// true
// 比较可以得出Teache 隐式原型 就是 Person类 可以获取到类的显示原型
console.log(Teacher.__proto__.prototype === Person.prototype)// true
const t = new Teacher('张三', '法律')
console.log('t', t)
// 1、要使用 t 的teach方法
// 2、t 没有 teach 方法 去 t的隐式原型__proto__去找 __proto__指向的是Teacher类的 prototype显示原型
// 4、在Teacher类的显示原型 prototype 找到 teach方法可以使用
console.log('teach', t.teach())
// 1、要使用 t 的drink方法
// 2、t 没有 teach 方法 去 t的隐式原型__proto__去找 __proto__指向的是Teacher类的显示原型 prototype
// 3、Teacher类.prototype显示原型没有,去Teacher类.__proto__隐式原型去找 Teacher类.__proto__ 指向 Person类
// 4、在Person类.prototype显示原型有 直接使用 drink方法
// 5、(我们当前这个Demo 是有的)如果没有去 Person类的__proto__隐式原型继续找
// t 实例对象中 t的__proto__>Teacher的proptype(找不到继续找他的)>Teacher的__proto__>Person的prototype 找到 drink方法
// 这一些列的 __proto__ proptype 组成的就是原型链
console.log('drink', t.drink())
// 检测当前对象是否有某个方法或属性
t.hasOwnProperty('name')