Skip to main content

`this` keyword in javascript

this keyword used to reference current object in javascript. There are two scenario where current object is determined differently.

* Calling object represented by `this` in function.

* Arrow function can reference object where the function defined.

To demonstrate the above scenarios we shall take some examples.

Suppose,

var x = 10;

(function() {
   console.log(this.x);
})() // 10

(() => {
   console.log(this.x);
})() // 10

There are two self executing functions both resulted in "10". At first look it seems behaving same, but there is basic deference what we going to see.

const xObj = {
    value: 10,
    getValue: () => {
        return this.value;
    }
};

const yObj = {
    value: 10,
    getValue: function () {
        return this.value;
    }
};

xObj.getValue(); // undefined
yObj.getValue(); // 10

Why undefined for `xObj`? Because arrow function is defined under object literal which is not a function itself. Object literal is not a function definition so `this` used inside object literal will not refer to the object. We can say that the arrow function is defined under global function, so `this` inside the arrow function points to global not to `xObj`.

`yObj`'s `getValue` points to its calling object. Here it is `yObj` own self.

Suppose there is

const zObj = {
    value: 20
};

zObj.getValue = yObj.getValue;

zObj.getValue(); // 20

`zObj` becomes calling object for normal function `getValue`, so `this` inside the function refers to `zObj`.

Arrow function statically binds to `this` where the arrow function is created. Arrow function is not seems useful when used with object literal defined in global context but it is helpful in some situation when we are using functional constructor to create object.

const xFunc = function () {
    this.value = 10;
    this.getValueArrow = () => {
        return this.value;
    };
    this.getValueNormal = function () {
        return this.value;
    };
};

const xf = new xFunc();

xf.getValueArrow() // 10

xf.getValueNormal(); // 10

Here, both calling object and object in which the functions defined are same. So, it looks like both function works same way, but they aren't.

const yFunc = function () {
    this.value = 20;
};

const yf = new yFunc();

yf.getValueArrow = xf.getValueArrow;

yf.getValueNormal = xf.getValueNormal;

yf.getValueArrow(); // 10

yf.getValueNormal(); // 20

Here `getValueArrow` function's `this` will statically bind to object created by functional constructor where the arrow function defined in, so it resulted in "10" as value from statically bounded `this`.

Whereas `getValueNormal` function's `this` will dynamically bind to calling object and reflects values from it. 

Comments

Popular posts from this blog

Basics of quantum computing: change of basis

Computing requires classical bits, which can hold a value of 0 or 1. Quantum computing gets benefit from superposition of quantum bit (qubit). Qubit is a representation of state of quantum object (electron, proton, photon, etc). The qubit holds a value between 0 and 1 while it is in superposition state. Superposition means the qubit possesses multiple values at the same time so we can harness its power for parallel computing. Once we try to measure the value it can be collapsed into either 0 or 1 based on probability. (Observer collapses wave function simply by observing.) Using bloch sphere, we can represent qubit physically. (The bloch sphere is a physical model to represent a spin state of qubit) A state vector can point to any direction from the center of the sphere. If a vector points to Z+ and Z-, it represents 0 and 1 state respectively. All other vectors represent superposition state in a Z basis. Now, if a vector points to X+, X-, Y+, Y-, all are at a 90-degree angle from

Monad: in programming

Monad is a structure with type constructor M and two functions unit ( η) and multiplication ( μ). and   To lift value from a to Ma we need unit function and to flatten from M(Ma) to Ma we need multiplication . Why do we need monad in functional programming? Why do we need functional programming anyways? Functional programming is a paradigm which uses pure functions to build an application. The power of pure functions are, we can compose them and we can build complex things out of the small and simple functions. If we have these functions   and   We can get   We can use below general purpose compose function to compose any two pure functions.   If we need to compose three functions then we can do like Now, we can't build application using only pure functions. It is next to impossible. We need side effects anyways to make the application practical in use. To achieve the goal, we need to keep pure functions in center/core part of application and need to move side effects outsid

Monad: to programming from category theory

We have seen the summarized article "monad in programming" in the previous post. Let's find out what is a monad in category theory and how the concept became relevant for functional programming. First, we need to understand the basics of category theory. Category A category consists of objects and morphisms (relationships) between those objects. More of it, the morphisms should be composable too. Below is an example of a category. Each dot is an object and each arrow shows morphism from some object to another. As arrows are composable, if there is a morphism from object a to object b , and there is another morphism from b to c , then we can find a morphism from a to c .  If you notice, there is identity morphism too, it exists for each object, but we have shown it just for x . It is a morphism from an object to itself. If we compose identity morphism with any other morphism w , we get the same w in return. Functor A functor is a relationship between categories