Javascript Prototypal Inheritance?

后端 未结 5 2057
日久生厌
日久生厌 2021-02-04 05:43

I\'been doing some inheritance in js in order to understand it better, and I found something that confuses me.

I know that when you call an \'constructor function\' with

5条回答
  •  無奈伤痛
    2021-02-04 06:13

    Answer by numbers to your questions:

    1. Object's prototype property is not called prototype. The standard uses [[prototype]] to designate it. Firefox makes this property public under the name of __proto__.
    2. The inheritance chain is [obj][prototype object]. Your original assumption ([obj][constructor][prototype]) is incorrect and you can easily disprove it by modifying constructor and/or constructor.prototype, and checking what methods can be called on your [obj] — you will discover that these modifications do not change anything.
    3. prototype property on objects are not checked and not used. You can set it to whatever you like. JavaScript uses it on function objects only during the object construction.

    To demonstrate the #3 here is the code from Dojo:

    dojo.delegate = dojo._delegate = (function(){
      // boodman/crockford delegation w/ cornford optimization
      function TMP(){}
      return function(obj, props){
        TMP.prototype = obj;
        var tmp = new TMP();
        if(props){
          dojo._mixin(tmp, props);
        }
        return tmp; // Object
      }
    })();
    

    As you can see it takes advantage of the fact that prototype is used only in one place by reusing the same function TMP for all delegated objects with different prototypes. In fact prototype is assigned directly before invoking the function with new, and it will be changed after that not affecting any created objects.

    You can find the object created sequence in my answer to Relation between [[Prototype]] and prototype in JavaScript.

提交回复
热议问题