开发者

Setting a variable as an array which can be accessed/updated by every function in an object?

Apologies if this isn't a well constructed post - I'm writing it on my phone because I'm in a meeting but can't get this out of my head!

I've created an object, as follows:

   /* CLASS = "HPAnalysisObject" */

    /* CONSTRUCTOR */
    var HPAnalysisObject = {
        points_total: new Array(),

        getHPTotals: function(house_id, label) {
            for (var i = 1; i <= 26; i++) { 
                initial = String.fromCharCode(64 + i);
                Frog.API.get("users.search", {
                    "params": {"surname": initial, "group": house_id},
                    "onSuccess": this.addUsers
                });
            }

            alert(this.getArray());
        },

        getArray: function() {
            return this.points_total;
        },
开发者_运维百科
        setArray: function(array) {
            alert(typeof(array));
        },

        addUsers: function(data) {
            array = new Array(this.getArray);

            for (var i = 0; i < data.length; i++) {
                if (data[i].profile.id == 200) {
                    array.push(data[i].id);
                }
            }

            this.setArray(array);
        }

    };

    widget.onLoad = function(){
        HPAnalysisObject.getHPTotals(10705, "eagles");
    }

The getArray function throws:

TypeError: not a function.

How do you, pseudo, initialise an empty array on init; put new items into that array with one function; then return the array with another?

EDIT: I HAVE OVERHAULED MY PSEUDO-CODE WITH THE ACTUAL CODE


"onSuccess": this.addUsers

The problem is, once the addUsers function is assigned to this property, you're losing the original this scope. One quick solution (that doesn't require a lot of restructuring) is to use a Function.prototype.bind polyfill:

"onSuccess": this.addUsers.bind(this)

But, the more proper fix is to restructure your code to use a closure. With a closure, you can define functions that are "private" and bound to your object instance. Something in the lines of:

var HPAnalysisObjectClass = (function () {
    var points_total = []; // "private"

    function addUsers(users) { // "private"
        // Use points_total, not this.points_total
    }

    return {
        addUsers: addUsers, // Make a "public" copy

        getHPTotals: function () {
            // ...
                Frog.API.get("users.search", {
                    "params": {"surname": initial, "group": house_id},
                    "onSuccess": addUsers // not this.addUsers!
                });
            // ...
        }
    };
})();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜