原型、原型链、构造函数、实例的关系

如图所示:
在这里插入图片描述
1.instanceof检测构造函数与实例的关系:

function Person () {.........}

person = new Person ()

res = person instanceof Person

res  // true

2.实例继承原型上的定义的属性:

function Person () {........}

Person.prototype.type = 'object n'

person = new Person ()

res = person.type

res  // object n

3.实例访问 ===> 原型

实例通过__proto__访问到原型 person.proto=== Person.prototype

4.原型访问 ===> 构造函数

原型通过constructor属性访问构造函数 Person.prototype.constructor === Person

5.实例访问===>构造函数

person.proto.constructor === Person

二、原型链
在读取一个实例的属性的过程中,如果属性在该实例中没有找到,那么就会循着 proto 指定的原型上去寻找,如果还找不到,则寻找原型的原型:

1.实例上寻找

function Person() {}

    Person.prototype.type = "object name Person";

    person = new Person();

    person.type = "我是实例的自有属性";

    res = Reflect.ownKeys(person); //尝试获取到自有属性

    console.log(res);

    res = person.type;

    console.log(res); //我是实例的自有属性(通过原型链向上搜索优先搜索实例里的)

2.原型上寻找

function Person() {}

    Person.prototype.type = "object name Person";

    person = new Person();

    res = Reflect.ownKeys(person); //尝试获取到自有属性

    console.log(res);

    res = person.type;

    console.log(res); //object name Person

3.原型的原型上寻找

function Person() {}

    Person.prototype.type = "object name Person";

    function Child() {}

    Child.prototype = new Person();

    p = new Child();

    res = [p instanceof Object, p instanceof Person, p instanceof Child];

    console.log(res); //[true, true, true] p同时属于Object,Person, Child

    res = p.type; //层层搜索

    console.log(res); //object name Person (原型链上搜索)

    console.dir(Person);

    console.dir(Child);

4.原型链上搜索

  1. 原型同样也可以通过 proto 访问到原型的原型,比方说这里有个构造函数 Child 然后“继承”前者的有一个构造函数 Person,然后 new Child 得到实例 p;

  2. 当访问 p 中的一个非自有属性的时候,就会通过 proto 作为桥梁连接起来的一系列原型、原型的原型、原型的原型的原型直到 Object 构造函数为止;

  3. 原型链搜索搜到 null 为止,搜不到那访问的这个属性就停止:

function Person() {}

  Person.prototype.type = "object name Person";

  function Child() {}

  Child.prototype = new Person();

  p = new Child();

  res = p.__proto__;

  console.log(res);         //Person {}

  res = p.__proto__.__proto__;

  console.log(res);         //Person {type:'object name Person'}

  res = p.__proto__.__proto__.__proto__;

  console.log(res);         //{.....}

  res = p.__proto__.__proto__.__proto__.__proto__;

  console.log(res);         //null
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值