javascript原型以及原型链总结

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);
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值