Is there a functional purpose for setting a variab

2019-03-05 08:37发布

问题:

This question already has an answer here:

  • How to access the correct `this` inside a callback? 10 answers

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?

回答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();


回答2:

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.



回答3:

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)
   });
};


回答4:

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>


回答5:

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.