JavaScript interview question

Explain var self = this in JavaScript?

Answer

The self is being used to maintain a reference to the original this even as the context is changing. It is a technique often used in event handlers ( especially in closures ).

this is a JavaScript keyword which refers to the current context. Unlike other programming languages, JavaScript does not have block scoping ( in C open/close {} curly braces refers to a block ). JavaScript has two scopes namely, global and local scope.

Example:

/**
 * this Context
 */
const context = {
  prop: 10,
  getCurrentContext: function () {
    return this.prop;
  }
};

console.log(context.getCurrentContext()); // 10

Note: 'self' should not be used this way anymore, since modern browsers provide a global variable self pointing to the global object of either a normal window or a WebWorker.

More Technical Interview Topics