Javascript revealing module pattern, public properties

前端 未结 2 440
傲寒
傲寒 2020-12-28 14:30

I\'m trying to get my head round the revealing module pattern in javascript. I\'m puzzled by two things about the following code snippet.

        var Child =         


        
相关标签:
2条回答
  • 2020-12-28 15:25

    This is slightly different solution, that doesn't require a getter/setter and preserves totalPoints as a property.

        var Child = function () {
    
            var _api;
    
            return _api = {
    
                addPoints: addPoints,
                points: 100
            };
    
            /* ----------- */
    
            function addPoints(points) {
                _api.points += points;
                return _api.points;
            };
    
        };
    
    0 讨论(0)
  • 2020-12-28 15:26

    You're passing a number here:

    return {
        points: totalPoints,
        addPoints: addPoints
    };
    

    This piece of code is no different from:

    return {
        points: 100,
        addPoints: addPoints
    };
    

    You're passing the value; not a reference to totalPoints (the latter is not possible in JavaScript). So when totalPoints changes, the value in the object does not.


    Using a function

    The simplest way to get around this is to use a function to get the most up-to-date result (like getPoints which you already have). This JSFiddle gives a complete example:

    return {
        points: function(x) { return totalPoints; }, // always up-to-date
        addPoints: addPoints
    };
    

    The downside is that the caller must now ask for points as a function call:

    console.log(george.points());
    

    Using a getters and setters

    Another solution is using getters which would enable you to get an updated value with just george.totalPoints, though getters are not widely supported (yet). You could implement a getter like this:

    var obj = {};
    
    obj.points = addPoints;
    
    // add a "special" property to the object instead of normal notation
    Object.defineProperty(obj, "totalPoints", {
        get: function() { // function that's executed when you use `.totalPoints`
            return totalPoints;
        }
    });
    
    return obj;
    

    Secondly, dropping var makes the functions global which is correct but not advisable. You could make one var statement using commas, if that's what you mean:

    var totalPoints = 100, // expands to three `var` statements, so no
        addPoints = ...,   // global variables
        getPoints = ...;
    
    0 讨论(0)
提交回复
热议问题