开发者

Use of 'this' in a JavaScript object using jQuery

开发者 https://www.devze.com 2023-03-20 08:19 出处:网络
Lately I\'ve been trying to make an object in JavaScript with the following structure: function col开发者_Python百科orDiv(div){

Lately I've been trying to make an object in JavaScript with the following structure:

function col开发者_Python百科orDiv(div){
      this.div=div;
      this.div.bind("click",this.changeColor)
      this.changeColor(){
            this.div.css("background", "#FF0000");
      }
}

The problem is that the changeColor method cannot be called from the jQuery environment because this must refer to the current colorDiv object, so the bind method cannot work as expected. How can this be solved?


There are a couple ways. The simplest is as follows:

function ColorDiv(div) {
      var that = this;

      that.div = div;
      that.div.bind("click", that.changeColor);

      that.changeColor = function () {
            that.div.css("background", "#FF0000");
      };
}

var colorDiv = new ColorDiv($("#my-div"));
$("#something-else").click(colorDiv.changeColor);

You save a reference to this in the variable that, which is just the name commonly used in the JavaScript world for exactly this purpose. Then you refer to that instead of this inside your changeColor method. (Note that I used that everywhere, just for consistency, even though the only place it actually makes a difference is inside the changeColor method.)


Another is to use the Function#bind method. You can either use it every time you call changeColor, like so:

var colorDiv = new ColorDiv($("#my-div"));
$("#something-else").click(colorDiv.changeColor.bind(colorDiv));

or you can use it in the ColorDiv class to ensure that all methods are bound correctly whenever they are called:

this.changeColor = (function () {
    this.div.css("background", "#FF0000");
}).bind(this);

As noted in the linked article, Function#bind is not supported in all browsers, so you'll need a shim like the one they give, or possibly a full-fledged ES5 shim.

Underscore.js has a bindAll function that could be useful here, too, especially with multiple methods:

_.bindAll(this);

Finally, it's worth noting you don't really need to do any of this in your particular example: just do

this.changeColor = function () {
    div.css("background", "#FF0000");
};

instead of what you have, i.e. reference the div variable passed in, instead of the reference stored in this.div, since they are the same thing.


Try setting as the first line of the method:

var self = this;

and then using self as needed.

this.div.bind("click",self.changeColor)
0

精彩评论

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