0

As in, sometimes when I look at code by other people, they will go var self = this; or in jquery for example, go var $self = $(this);

is there a particular reason for doing so?

user2864740
  • 60,010
  • 15
  • 145
  • 220
slynthin
  • 65
  • 3
  • 4
    Yes, if you want to reference the value of `this` in another function (closure). See http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback – Felix Kling Aug 16 '14 at 21:35
  • Yes, whenever you wish to access properties of that object in a context where `this` will refer to, instead, another object. – Anthony Forloney Aug 16 '14 at 21:36
  • http://stackoverflow.com/questions/4813119/accessing-this-in-javascript-closure – user2864740 Aug 16 '14 at 21:41
  • I have read through the entire thing. I'm just confused with this line 'That's why an easy solution is to simply create a new variable that also refers to that object.' In the example, are you essentially making it 'self.data = data;'? And if so, what is self? I thought the point of using 'this' was so that it would refer to whatever object called it – slynthin Aug 16 '14 at 22:28
  • @slynthin: `self` has the same value as `this`, so yes, it will refer to a new instance of `MyConstructor`. But I also want to be able to refer to that object inside the event handler. I can't use `this` because `this` has a different value inside the event handler. So I'm keeping a reference to the value of the original `this` in a separate variable. – Felix Kling Aug 17 '14 at 01:14

5 Answers5

1

It preserves the value of this for use in functions defined inside the current function.

// Contrived example
var myObject = {
    func: function () {
        var self = this;
        setTimeout(bar, 1000);

        function bar () {
            alert(this); // `window`
            alert(self); // `myObject`
        }
    }
};
myObject.func();
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

By holding a reference to this in some context, you have the ability to access it in other contexts such as within member functions or forEach loops.

Consider the following example:

function ViewModel() {
   var self = this;

   self.linksArray = ["link1", "link2", "link3"];

   self.linksArray.forEach(function(link) {
       // this refers to the DOM window
       // and self refers to the parent context (ViewModel)
   });
};
PaulDapolito
  • 824
  • 6
  • 12
  • so if you set a variable to this while this is in a particular context you can put the variable in another context (not the original) and the variable is still equal to the value of this in the original context? – slynthin Aug 16 '14 at 21:46
1

As others have mentioned, you could set a variable to $(this) if you wish to use it in another function.

On practical example would be when doing an ajax call tied to an event on the page. Using JQuery:

<script>

        $(document).on("click", ".mySelector", function () {
            // Where we are in the click event, $(this) refers to whatever
            // element has a class of mySelector that was clicked
            var self = $(this);
            theDiv.html('');
            $.ajax({
                cache: false,
                type: "GET",
                url: "/SomeAjaxMethod",
                data: { },
                success: function (data) {
                    // Trying to access $(this) here will return undefined, as
                    // we are technically in the callback method
                    // Where our event is based on a class, there is likely more
                    // than one element on the page with the class, so it would be
                    // difficult to get the exact element again without some other code
                    self.html(data);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert("Ajax failed.")
                }
            }); // end ajax call
        }); // end on mySelector class click
</script>

or:

<script>
    $(document).ready(function () {
        $('.foo').click(function () {
            var self = $(this);           // Whatever element that was clicked with foo class
            $('.bar').each(function () {
                var bar = $(this);        // Current iteration of bar element in the loop
                var baz = self;           // self is still the initial value, but $(this) is not
            }); // end bar loop
        }); // end foo click
    }); // end doc ready
</script>
0

The particular example (not using JQuery) is the function closure. Referencing this in a function closure refers to the function object, not the context in which the closure was defined. Your example is one way to deal with the closure problem:

var that = this;
function(){
   that.something = 1;
}();

Another way to deal with this is with the apply method on the function:

function(arg){
   this.something = 1;
}.apply(this, argumentArray);

The first argument in apply is the "this argument" that "this" will refer too.

Charles Smartt
  • 349
  • 2
  • 8
0

One purpose of that would be to make this accessible to inner functions. for example:

function clickHandler(){
  console.log(this); // this is body
  var $self = this;
  function inner(){
    console.log(this); // this is window
    console.log($self); // this is body
  }
  inner();
}
$("body").click(clickHandler);

Run it in console to get a sense.

Alireza Mirian
  • 5,862
  • 3
  • 29
  • 48