__proto__ VS. prototype in JavaScript

后端 未结 30 1995
爱一瞬间的悲伤
爱一瞬间的悲伤 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:48

    !!!THIS IS THE BEST EXPLANATION IN THE WORLD!!!!!

    var q = {}
    var prototype = {prop: 11}
    
    q.prop // undefined
    q.__proto__ = prototype
    q.prop // 11
    

    in function constructors javascript engine call this q.__proto__ = prototype automatically when we write new Class, and in to the __proto__ prop set Class.prototype

    function Class(){}
    Class.prototype = {prop: 999} // set prototype as we need, before call new
    
    var q = new Class() // q.__proto__ = Class.prototype
    q.prop // 999
    

    Enjoy %)

提交回复
热议问题