__proto__ VS. prototype in JavaScript

后端 未结 30 1911
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 06:14

This figure again shows that every object has a prototype. Constructor function Foo also has its own __proto__ which is Function.prototype, a

30条回答
  •  攒了一身酷
    2020-11-21 06:47

    This is a very important question relevant to anyone who wants to understand prototypical inheritance. From what I understand, prototype is assigned by default when an object is created with new from a function because Function has prototype object by definition:

    function protofoo(){
    }
    var protofoo1 = new protofoo();
    console.log(protofoo.prototype.toString()); //[object Object]
    

    When we create an ordinary object without new, ie explicitly from a function, it doesn't have prototype but it has an empty proto which can be assigned a prototype.

    var foo={
      check: 10
    };
    console.log(foo.__proto__); // empty
    console.log(bar.prototype); //  TypeError
    foo.__proto__ = protofoo1; // assigned
    console.log(foo.__proto__); //protofoo
    

    We can use Object.create to link an object explicitly.

    // we can create `bar` and link it to `foo`
    var bar = Object.create( foo );
    bar.fooprops= "We checking prototypes";
    console.log(bar.__proto__); // "foo"
    console.log(bar.fooprops); // "We checking prototypes"
    console.log(bar.check); // 10 is delegated to `foo`
    

提交回复
热议问题