Why is the 'this' alias in JS so error prone?

Reading The principles for writing consistent, idiomatic JavaScript in a section titled “Faces this” suggests that the thisJavaScript alias is “extremely error prone”.

I personally try to use _.bind()(or something similar) whenever possible, but does anyone know why aliasing is thisso error prone?

+5
source share
2 answers

There are four meanings that thiscan take, depending on how it was called. Accordingly, it is necessary to monitor what type is thisused, and I can think of thissimple problems in at least 3/4 of them.

Called as a Method

In obj.myFunc(), thisattached to obj.

This can be scary if passed in a callback myFuncbecause it forgets that it was once part of an object and was called autonomous. See What does "var that = this;" mean? in javascript? for the usual workaround.

Called as a standalone function

In plain myFunc(), thisbinds to a global object.

Called as constructor

new myFunc() ( ! , new, , ). , this () .

, new, , , , . , JSLint (IIRC).

( )

myFunc.apply(obj, args), this obj. , , this .

+7

this, , , , this . , this, , , . :

$('#something').click ( function (e) {
    //this refers to the clicked element
    var _this = this;  //Tracking a reference to the clicked element `this`
    $.each(someArray, function(index, value) {
       //this refers to the current element being iterated in someArray
       $.ajax({
          url : 'some/path',
          success: function (res) {
             //this refers to the ajax request
             //_this still references the clicked element
          } 
       })
    })
})

, this this (, ajax), - . .

+4

All Articles