JavaScript - this vs self


#1

JavaScript - this vs self - Can someone explain the difference between self and this and when to use self or this in Javascript


#2

Short version:
You never use self in JavaScript. This is simply not a thing in JS. self is Pythons equivalent of this.


Long version (based on this post):
Should you come to the point of defining functions in JavaScript, you will soon find that this points to the functions context rather than the global context. A common trick is to assign (the global) this to another variable. As self is almost the same as this, it’s one of the most common names for this helper-variable. So unless you assign anything to self it is just nonexistent.

var self = this;

function getGoldThis(){
    return this.gold;    //this would fail, because the current context doesn't know this.gold
}

function getGoldSelf(){
    return self.gold;    //this would work, as it uses the this.gold from the outer context
}

var thisEquals = (this.gold == getGoldThis());    //false
var selfEquals = (this.gold == getGoldSelf());    //true