对javascript中原型链的理解

我总结的规律如下

  1. 函数是一种对象,对象不一定是函数
  2. 函数的构造函数为Function函数
  3. 函数的prototype属性包含一个自有属性constructor,指向函数自身(前提:函数的prototype未被重写)
  4. 对象的原型(__proto__)指向其构造函数的prototype
  5. 特殊对象Function.prototype的原型(__proto__)指向Object.prototype
  6. 特殊对象Object.prototype的原型(__proto__)指向null,到达原型链顶端
  7. 自定义函数的prototype属性的原型(__proto__)指向Object.prototype(自定义函数的prototype属性也是一个对象,其构造函数为Object)
    备注:所总结的仅作为个人学习笔记,如有纰漏之处还望指正

示例

  1. Object的原型链
    Object — Function.prototype — Object.prototype — null
    推导过程:
    Object.__proto__ === Function.prototype【2】
    Function.prototype.__proto__ === Object.prototype【5】
    Object.prototype.__proto__ === null【6】
    原型链为:
    Object — Function.prototype — Object.prototype — null
Created with Raphaël 2.1.0 Object Function.prototype Object.prototype null
  1. 自定义对象的原型链
    function ClassA(){}
    var objA = new ClassA();
    推导过程:
    objA.__proto__ === ClassA.prototype【4】
    ClassA.prototype.__proto__ === Object.prototype【7】
    Object.prototype.__proto__ === null【6】
    原型链为:
    objA — ClassA.prototype — Object.prototype — null
Created with Raphaël 2.1.0 objA ClassA.prototype Object.prototype null
  1. 继承关系对象的原型链
    function ClassA(){}
    function ClassB(){}
    ClassB.prototype = new ClassA();
    ClassB.prototype.constructor = ClassB;
    var objB = new ClassB();
    推导过程:
    objB.__proto__ === ClassB.prototype【4】
    ClassB.prototype.__proto__ === ClassA.prototype【4】
    ClassA.prototype.__proto__ === Object.prototype【7】
    Object.prototype.__proto__ === null【6】
    原型链为:
    objB — ClassB.prototype — ClassA.prototype — Object.prototype — null
Created with Raphaël 2.1.0 objB ClassB.prototype ClassA.prototype Object.prototype null

猜你喜欢

转载自blog.csdn.net/attwice/article/details/50442382