How can I keep the context of 'this' in jquery

前端 未结 6 1935
情话喂你
情话喂你 2020-12-31 20:11

I have something like this:

var Something = function(){
  this.render = function(){};
  $(window).resize(function(){
    this.render();
  });
}
6条回答
  •  一个人的身影
    2020-12-31 20:29

    That's exactly what I do. It's not specific to jQuery, either.

    var Construct = function() {
        var self = this; //preserve scope
    
        this.materials = 2000;
    
        this.build = function(){
            self.materials -= 100;
        };
    };
    

    Remember to use the var keyword in front of your new scope variable. Otherwise, you're creating a new global variable. As a local variable, it will still be accessible inside the inner function via a closure.

提交回复
热议问题