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

前端 未结 6 1933
情话喂你
情话喂你 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:28

    The best solution, to keep variables at a minimum would be to use the Function.prototype.bind() method.

    var Something = function(){
      this.render = function(){};
      $(window).resize( this.render.bind( this ) );
    }
    

    The problem with this method that may cause future complications, which means you should choose to use it sparingly, is when you need to invoke $(this) to grab the element. So, I might suggest that it would be worthwhile to use Function.prototype.bind() in your resize method, but it would not be a good solution to use it in a click function that you might need to target the clicked element directly.

    See this JSFiddle for a working example.

    See the Mozilla Documentation on Function.prototype.bind() for more information

    The other methods are usable, but creating a variable to maintain the context of this is the undesired effect according to your question.

提交回复
热议问题