Context in Javascript: Self vs. This

Jackson Beytebiere
2 min readNov 16, 2020

What is the difference between ‘self’ and ‘this’? The answer can seem a bit unclear and murky at first. But understanding the difference between the two can be helpful and lead one to becoming a better object oriented programmer.

Let’s start with ‘this’. ‘this’ is a keyword. It is used to refer to an object in which a method is called. For example:

However ‘this’ can lose its scope easily. If we were to do something like this with the previous example:

We can see that it would print out ‘undefined’. This is because ‘this’ default is window. It may seem a bit strange that this happened. ‘this’ will only work in our first example if it is called via a property access operation. With a property access operation the function is passed that object as the value of its ‘this’. Otherwise, ‘this’ defaults to the global object, which is window in a browser.

Another use for ‘this’ is in an object constructor. In one, ‘this’ refers to an object being made, or myPoint in the example below. This is because we used the keyword ‘new’ thus making the operation a class instantiation. During class instantiation, ‘this’ refers to the new object.

‘self’ is an identifier, It has no special syntactic meaning. Browsers define window.self as window. Self can be redefined within an enclosing scope.

When calling a function in the global scope, both ‘self’ and ‘this’ defaults to window. However, when not in the global scope, ‘this’ will refer to that context but ‘self’ will still refer to window. Hopefully this explanation provided you with a sense of ‘self’.

references: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind, https://stackoverflow.com/a/16876159, https://www.quora.com/What-is-an-explanation-as-to-why-self-is-needed-instead-of-this-in-JavaScript

--

--

Jackson Beytebiere

I write about programming and specifically CSS | HTML | JavaScript | Ruby | React.js | Redux.