参考教程:https://www.bilibili.com/video/BV1Q64y1v7fW?p=1
学习一样东西之前,先了解它的作用,这样往往会让你的学习目的更加明确。
js中的原型、原型链,用来实现继承,继承有什么用嘞?就是可以把共享的东西抽象成一个父类,然后通过继承这个父类,来复用共有的属性、方法
1、继承
js中的继承,实现原理是基于原型的。明确以下几个概念:
- 对象是由函数构造的
- js中,万物皆对象,函数也是对象
- 函数具有显式原型,prototype(也有对象的隐式原型_proto_)
- 对象有隐式原型,_proto_
testObj = new testFn();
testObj._proto_ = testFn.prototype;
2、例子
function Person(name, sex){
this.name = name;
this.sex = sex;
}
// 把方法写在原型上,可以被继承
Person.prototype.drink = function(){
console.log('drink');
}
function Teacher(subject){
this.subject = subject;
}
// 先继承,再添加
Teacher.prototype = new Person();
Teacher.prototype.teach = function(){
console.log('teach:' + this.subject);
}
const teacher = new Teacher('math');
teacher.teach();
teacher.drink();
teacher.name = 'lily';
console.log(teacher.name);
// console.log(teacher.sex); //undefined
3、原型链
像上例中,teacher对象,可以到Teacher函数中找到 teach() 方法,到Person函数中找到 drink() 方法。
为什么能够按照这样子的顺序来找呢?因为它们处于同一条原型链上!
teacher._proto_ === Teacher.prototype
Teacher._proto_ === Person.prototype
Person._proto_ === Object.prototype
Object._proto_ === null
这也就是_proto_被叫做隐式原型的原因吧?(我猜的!!)
js中,万物皆对象,所以最终都会指向Object类
举例:instanceof 就是利用原型链来判断,是否属于某个数据类型
console.log(teacher instanceof Teacher);
console.log(teacher instanceof Person);
console.log(teacher instanceof Object);
// 全为true