Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set "this" variable easily?

People also ask

What is this variable?

In JavaScript, “this” variable is a variable that every execution context gets, in a regular function call. Every JavaScript function has a reference to its current execution context while executing, called this. Execution context means here means the manner of calling of functions.

Can we assign this to variable JavaScript?

Yes, this is accepted practice.

How does the this keyword work?

In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.

Can you give an example of one of the ways that working with this has changed in ES6?

Can you give an example of one of the ways that working with this has changed in ES6? ​ ES6 allows you to use arrow functions which uses the enclosing lexical scope. This is usually convenient, but does prevent the caller from controlling context via .


There are two methods defined for all functions in JavaScript, call(), and apply(). The function syntax looks like:

call( /* object */, /* arguments... */ );
apply(/* object */, /* arguments[] */);

What these functions do is call the function they were invoked on, assigning the value of the object parameter to this.

var myFunction = function(){
    alert(this.foo_variable);
}
myFunction.call( document.body );

I think you're looking for call:

myFunction.call(obj, arg1, arg2, ...);

This calls myFunction with this set to obj.

There is also the slightly different method apply, which takes the function parameters as an array:

myFunction.apply(obj, [arg1, arg2, ...]);

If you want to 'store' the this value to a function so that you can call it seamlessly later (e.g. when you don't have access to that value anymore), you can bind it (not available in all browsers though):

var bound = func.bind(someThisValue);

// ... later on, where someThisValue is not available anymore

bound(); // will call with someThisValue as 'this'

My search on how to bind this brought me here so I am posting my findings: In 'ECMAScript 2015' we can also set this lexically using arrow functions to.

See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Instead of:

function Person() {
  setInterval(function growUp() {
    // The callback refers to the `self` variable of which
    // the value is the expected object.
    this.age++;
  }.bind(this), 1000);
}

We can now do:

function Person(){
  this.age = 0;

  setInterval(() => {
    this.age++; // |this| properly refers to the person object
  }, 1000);
}

var p = new Person();

Setting the this keyword in javascript.

Javascript has 3 built in methods for setting the this keyword conveniently. They are all located on the Function.prototype object so every function can use them (since every function inherits from this prototype via prototypal inheritance). These functions are the following:

  1. Function.prototype.call(): This function takes the object which you want to use as this as a first argument. Then the remainder of the arguments are the respective arguments of the function which is called.
  2. Function.prototype.apply(): This function takes the object which you want to use as this as a first argument. Then the second argument is an array which contains the values of the arguments of the function which is called (first element of array is first argument of the function, second argument of the array is second argument of function etc.).
  3. Function.prototype.bind(): This function returns a new function which has a different value of this. It takes the object which you want to set as the this value as a first argument and then returns a new function object.

Difference between call/apply and bind:

  • call and apply are similar in the fact that they immediately call the function (with a predefined value of this)
  • bind is different from call and apply in the fact that this function returns a new function with a different binding of the this value.

Examples:

const thisObj = {
  prop1: 1,
  prop2: 2,
};

function myFunc(arg1, arg2) {
  console.log(this.prop1, this.prop2);
  console.log(arg1, arg2);
}

// first arg this obj, other arguments are the  
// respective arguments of the function
myFunc.call(thisObj, 'Call_arg1', 'Call_arg2');

// first arg this obj, other argument is an array which  
// are the respective arguments of the function
myFunc.apply(thisObj, ['Apply_arg1', 'Apply_arg2']);


// the bind method returns a new function with a different
// this context which is stored in the newMyFunc variable
const newMyFunc = myFunc.bind(thisObj);

// now we can call the function like a normal function 
newMyFunc('first', 'second');