How to call a method inside a javascript object

后端 未结 5 579
北荒
北荒 2021-02-08 17:30

I\'m just learning about how to best organize my javascript code, and I had a question regarding this small piece of code I wrote:

var reportsControllerIndex = {         


        
5条回答
  •  一生所求
    2021-02-08 18:05

    You can write it likes this:

    var reportsControllerIndex = new function () {
    
        var self = this;
    
        self.plotMapPoints = function (data) {
            //plots points
        },
    
        self.drawMap = function () {
            $.getJSON('/reports.json', function (data) {
                self.plotMapPoints(data);         
            });
        },
    
        self.run = function () {
            self.drawMap();
        }
    };
    

    This class will works as same as you did, and you can still call the class method by:

    reportsControllerIndex.run()
    

    In this paradigm, I defined self pointing to the class itself, so that you can call self wherever you want in the class.


    Farther, this paradigm can solve the this problem in the function that you bring as callback to another funciton:

    plotMapPoints: function(data) {
        console.log(this);
        // Need a this referring to the class itself
        // It's inconvenient to bring this as parameter
    },
    

提交回复
热议问题