美文网首页
原型和原型链

原型和原型链

作者: 王果果 | 来源:发表于2021-07-30 08:37 被阅读0次

    源网站:https://blog.csdn.net/xiaoermingn/article/details/80745117

    一、原型

    • 所有引用类型都有一个proto(隐式原型)属性,属性值是一个普通的对象
    • 所有函数都有一个prototype(原型)属性,属性值是一个普通的对象
    • 所有引用类型的proto属性指向它构造函数的prototype
    var a = [1,2,3];
    a.__proto__ === Array.prototype; // true
    

    二、原型链

    当访问一个对象的某个属性时,会先在这个对象本身属性上查找,如果没有找到,则会去它的proto隐式原型上查找,即它的构造函数的prototype,如果还没有找到就会再在构造函数的prototype的proto中查找,这样一层一层向上查找就会形成一个链式结构,我们称为原型链。

    function Parent(month){
        this.month = month;
    }
    
    var child = new Parent('Ann');
    
    console.log(child.month); // Ann
    
    console.log(child.father); // undefined
    
    
    • 在child中查找某个属性时,会执行下面步骤:


      image.png
    • 访问链路为:


      image.png
    • 一直往上层查找,直到到null还没有找到,则返回undefined
    • Object.prototype.proto === null
    • 所有从原型或更高级原型中的得到、执行的方法,其中的this在执行时,指向当前这个触发事件执行的对象

    相关文章

      网友评论

          本文标题:原型和原型链

          本文链接:https://www.haomeiwen.com/subject/ykeqvltx.html