It is said that all Javascript objects have a prototype property, but I only see foo.prototype if foo is a function?

前端 未结 2 863
深忆病人
深忆病人 2020-12-28 17:21

It is often said that every Javascript object has a prototype property, but I find that foo.prototype has a value only if foo is a fun

相关标签:
2条回答
  • 2020-12-28 18:10

    Every JavaScript object has an internal "prototype" property, often called [[prototype]], which points to the object from which it directly inherits. This is exposed in FF and Chrome by the non-standard __proto__ property. Object.getPrototypeOf is a getter for this internal property.

    Every JavaScript function [object] has a property prototype, which is initialized with an [nearly] empty object. When you create a new instance of this function by calling it as a constructor, the [[prototype]] of that new object will point to the constructor's prototype object.

    If you get the [[prototype]] of a function (every function is an object, so it has one), it will result in the Function.prototype object from which functions inherit their methods (like bind, call, apply etc). See also Why functions prototype is chained repeatedly? on that.

    0 讨论(0)
  • 2020-12-28 18:22

    It is the constructor of every Object that has a prototype. So for some foo, baror foobar:

    var foo = {};
    console.log(foo.constructor.prototype); //=> Object
    var bar = 5;
    console.log(bar.constructor.prototype); //=> Number
    function Foobar(){} 
    var foobar = new Foobar; //Foobar used a constructor
    console.log(foobar.constructor.prototype); //=> Foobar
    
    0 讨论(0)
提交回复
热议问题