Relation between [[Prototype]] and prototype in JavaScript

后端 未结 3 1601
别跟我提以往
别跟我提以往 2020-12-04 10:12

From http://www.jibbering.com/faq/faq_notes/closures.html :

Note: ECMAScript defines an internal [[prototype]] property of the internal Object type. This

3条回答
  •  忘掉有多难
    2020-12-04 10:37

    To answer your question directly: logically it is an object's private copy of the prototype property of its constructor. Using metalanguage this is how objects are created:

    // not real JS
    
    var Ctr = function(...){...};
    Ctr.prototype = {...}; // some object with methods and properties
    
    // the object creation sequence: var x = new Ctr(a, b, c);
    var x = {};
    x["[[prototype]]"] = Ctr.prototype;
    var result = Ctr.call(x, a, b, c);
    if(typeof result == "object"){ x = result; }
    // our x is fully constructed and initialized at this point
    

    At this point we can modify the prototype, and the change will be reflected by all objects of the class, because they refer to the prototype by reference:

    Ctr.prototype.log = function(){ console.log("...logging..."); };
    
    x.log();  // ...logging..
    

    But if we change the prototype on the constructor, already created objects will continue referring to the old object:

    Ctr.prototype = {life: 42};
    // let's assume that the old prototype didn't define "life"
    
    console.log(x.life);  // undefined
    x.log();              // ...logging...
    

    In the full accordance with the standard [[prototype]] is not available, but Mozilla extends the standard with __proto__ property (read-only), which is exposing the normally hidden [[prototype]]:

    • the Mozilla's documentation
    • overview of Mozilla's extensions: __count__, __proto__, __parent__

    Again, __proto__ can be legalized in the next ES3.1 standard.

提交回复
热议问题