How to call a method inside a javascript object

后端 未结 5 1459
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-08 17:23

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:00

    You want to store the this binding in a variable.

    drawMap: function() {
        var _this = this;
        $.getJSON('/reports.json', function(data) {
            _this.plotMapPoints(data);         
        });
    }
    
    0 讨论(0)
  • 2021-02-08 18:04
    plotMapPoints: function(data) {
        //plots points
    }.bind(this)
    

    when defining your function you can just add .bind(this) to set the correct context for that function.

    0 讨论(0)
  • 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
    },
    
    0 讨论(0)
  • 2021-02-08 18:14

    Late answer, but jQuery has a method called jQuery.proxy() that is made for this purpose. You pass it the function along with the value of this you want to retain, and it will return a function that ensures this is correct.

    This way you don't need to define a variable.

    drawMap: function() {
        $.getJSON('/reports.json', $.proxy(function(data) {
            this.plotMapPoints(data);         
        }, this));
    }
    
    0 讨论(0)
  • 2021-02-08 18:14

    You need to use a variable reference to this outside the getJSON function. getJSON sets the context of the callback within jquery.

    Like this:

    var self = this;
    $.getJSON('/reports.json', function(data) {
        self.plotMapPoints(data);         
    });
    
    0 讨论(0)
提交回复
热议问题