Setting javascript prototype function within object class declaration

前端 未结 5 637
既然无缘
既然无缘 2020-12-04 20:08

Normally, I\'ve seen prototype functions declared outside the class definition, like this:

function Container(param) {
    this.member = param;
}
Container.p         


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-04 20:46

    Sorry for resurrecting an old question, but I wanted to add something that I recently discovered somewhere else here on SO (looking for the link, will edit/add it once I find it): found it.

    I personally like the below methodology because I can visually group all my prototype and 'instance' definitions together with the function definition, while avoiding evaluating them more than once. It also provides an opportunity to do closures with your prototype methods, which can be useful for creating 'private' variables shared by different prototype methods.

    var MyObject = (function () {
        // Note that this variable can be closured with the 'instance' and prototype methods below
        var outerScope = function(){};
    
        // This function will ultimately be the "constructor" for your object
        function MyObject() {
            var privateVariable = 1; // both of these private vars are really closures specific to each instance
            var privateFunction = function(){};
            this.PublicProtectedFunction = function(){ };
        }
    
        // "Static" like properties/functions, not specific to each instance but not a prototype either
        MyObject.Count = 0;
    
        // Prototype declarations
        MyObject.prototype.someFunction = function () { };
        MyObject.prototype.someValue = 1;
    
        return MyObject;
    })(); 
    
    // note we do automatic evalution of this function, which means the 'instance' and prototype definitions 
    // will only be evaluated/defined once.  Now, everytime we do the following, we get a new instance
    // as defined by the 'function MyObject' definition inside
    
    var test = new MyObject();
    

提交回复
热议问题