Why declare properties on the prototype for instance variables in JavaScript

后端 未结 4 1894
清酒与你
清酒与你 2020-12-12 21:13

I\'m trying to get my head around this black art called JavaScript - and, I must admit, pretty excited about it. I\'ve been looking at code examples, mainly from \"easeljs\"

4条回答
  •  没有蜡笔的小新
    2020-12-12 21:31

    Other answers have already explained the difference between prototype vs instance properties.

    But just to add to the answer, let's break down your code snippet:

    (function(){                         // <------- 1
       // constructor
       function MyCircle(radius){        // <------- 2
           this.radius = radius;         // <------- 2.1
       }
       MyCircle.prototype.radius;        // <------- 3
       this.area = function(){           // <------- 4
           return 3.14*this.radius*this.radius;
       };
       window.MyCircle = MyCircle;       // <------- 5
    }());
    
    1. Creating an IIFE which acts as a scope container for the inner code
    2. Declaring a function called MyCircle using a constructor pattern (but observe that it never gets "constructed" so should probably get rid of the capital letter since it's misleading)
      • when invoked creates a radius instance property on the invoked object
    3. Attempting to access a radius property on MyCircle function's prototype which doesn't exist so evaluates to undefined
    4. Creating an area instance property on the global window object and assigning it a function expression
    5. Creating a MyCircle instance property on a window object and assigning to it the MyCircle function

    Summary: It seems like it's creating an area and MyCircle properties on the global window object, and when MyCircle is invoked it creates an additional radius property.

    Usage: MyCircle should be invoked before area since area relies on MyCircle initialising the radius:

    window.MyCircle(10);
    window.area(); // evaluates to 314
    

提交回复
热议问题