继承与原型链

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
在了解原型之前,先把以下几点引入脑海:

  1. 当谈原型时,JavaScript只有一种结构,那就是对象
  2. 每个JavaScript函数实际上都是一个Function实例对象。例:
    const sum = new Function('a', 'b', 'return a + b');
    console.log(sum(2, 6));

    翻译:sum函数是一个Function对象

  3. 在 JavaScript 中,函数(function)是允许拥有属性的。所有的函数会有一个特别的属性 —— prototype
    function doSomething(){}
    console.log( doSomething.prototype );
    
    
    {
        constructor: ƒ doSomething(),
        __proto__: {
            constructor: ƒ Object(),
            hasOwnProperty: ƒ hasOwnProperty(),
            isPrototypeOf: ƒ isPrototypeOf(),
            propertyIsEnumerable: ƒ propertyIsEnumerable(),
            toLocaleString: ƒ toLocaleString(),
            toString: ƒ toString(),
            valueOf: ƒ valueOf()
        }
    }
     
    
     
    
    function doSomething(){}
    doSomething.prototype.foo = "bar";
    console.log( doSomething.prototype );
    {
        foo: "bar",
        constructor: ƒ doSomething(),
        __proto__: {
            constructor: ƒ Object(),
            hasOwnProperty: ƒ hasOwnProperty(),
            isPrototypeOf: ƒ isPrototypeOf(),
            propertyIsEnumerable: ƒ propertyIsEnumerable(),
            toLocaleString: ƒ toLocaleString(),
            toString: ƒ toString(),
            valueOf: ƒ valueOf()
        }
    }

     



  4. 每个实例对象都有__proto__属性,它指向构造函数的原型对象(prototype)
    结合2可以把4翻译为:sum函数是Function的实例对象,所以它的__proto__指向Function.prototype 

    再看一个我们常用的普通的对象示例: 
      

    function LateBloomer() {
           this.petalCount = Math.ceil(Math.random() * 12) + 1;
    }
    var flower = new LateBloomer();
    console.dir(flower)

    这个flower对象的__proto__指向 LateBloomer.prototype


记住以上几条,再看下面的原型链图,请结合代码和输出结果一起看,原型链就会清楚一些。

posted on 2019-12-24 17:02  寒林白雨  阅读(164)  评论(0)    收藏  举报