Play Home Contribute GitHub Join Us Discourse Staff Members GitHub Contribution Guides Team

JavaScript - this vs self


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


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 would fail, because the current context doesn't know

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

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