1、构造函数、原型、实例三者之间的关系
构造函数有个指针指向原型
原型中有个指针指回构造函数
实例中有个指针指向原型
2、原型与继承的关系
从技术上讲,一个实例的原型链上有某个构造函数的原型,那么实例 instanceof 构造函数
的结果就为true,下面有几个例子
function Parent(name) {
this.name = name;
}
function Child(age) {
this.age = age;
}
//继承
Child.prototype = Object.create(Parent.prototype);
const p = new Parent();
const c = new Child();
console.log(p instanceof Parent); //true
console.log(c instanceof Parent);//true
function Child() {
}
Child.prototype = Object.create(Array.prototype);
console.log(new Child() instanceof Array); //true
function Child() {
}
Child.prototype = [];
console.log(new Child() instanceof Array); //true
为了排除实例的影响,我们直接更换原型
function Child() {
}
function Parent() {
}
Child.prototype = Parent.prototype;
console.log(new Child() instanceof Parent); //true
console.log(new Child() instanceof Child); //true
3、自定义原型链(继承)
// 工具继承函数
function inheritePrototype(subType, superType) {
subType.prototype = Object.create(superType.prototype, {
constructor: {
value: subType,
enumerable: false
}
});
subType.__proto__ = superType; //静态方法的继承
}
//爷爷
function Grandpa(nationality) {
this.nationality = nationality;
}
//
//爸爸
function Father(nationality, gender) {
this.gender = gender;
Grandpa.call(this, ...arguments);//继承构造函数里面的属性
}
inheritePrototype(Father, Grandpa); //爸爸继承爷爷的prototype
//
//儿子
function Son(nationality, gender, hobby) {
this.hobby = hobby
Father.call(this, ...arguments)//继承构造函数里面的属性
}
inheritePrototype(Son, Father);//儿子继承爸爸的protype
const son = new Son('China', 'male', 'programming');
console.dir(son);
console.log(son instanceof Grandpa); //true
console.log(son instanceof Father); //true
console.log(son instanceof Object); //true
// console.dir(Grandpa.prototype);
console.dir(Son);