Learn more about this example in javaScript and how it works

  • 2020-03-30 01:19:35
  • OfStack

How this works

If a function is called as a method of an object, this will be assigned to that object.


var parent = {
    method: function () {
        console.log(this);
    }
};

parent.method();
// <- parent


Note that this behavior is very "fragile". If you get a reference to a method and call it, the value of this is not parent, but window global object. This confuses most developers.


ThisClownCar();
// <- Window
 

Changes to this

The.call,.apply, and.bind methods are used to manipulate the way the function is called, helping us define the value of this and the value of the arguments passed to the function.

Function.prototype.call can have any number of arguments. The first argument is assigned to this, and the rest is passed to the calling Function.


Array.prototype.slice.call([1, 2, 3], 1, 2)
// <- [2]

Function.prototype.apply  The behavior and .call Similar, except that the argument it passes to the function is an array, not an arbitrary argument. 

String.prototype.split.apply('13.12.02', ['.'])
// <- ['13', '12', '02']
 

Function.prototype.bind creates a special Function that will always use the argument passed to. Bind as the value of this, as well as the ability to assign part of the argument to create a curride version of the original Function.

 


var arr = [1, 2];
var add = Array.prototype.push.bind(arr, 3);

// effectively the same as arr.push(3)
add();

// effectively the same as arr.push(3, 4)
add(4);

console.log(arr);
// <- [1, 2, 3, 3, 4]


This in the scope chain

In the following example, this will not remain unchanged in the scope chain. This is a flaw in the rules and often confuses amateur developers.


function scoping () {
  console.log(this);

  return function () {
    console.log(this);
  };
}

scoping()();
// <- Window
// <- Window

A common method is to create a local variable to hold a reference to this, and not to have a homologous variable in a subscope. A variable of the same name in the child scope overrides the reference to this in the parent scope. http://www.cnblogs.com/sosoft/

 
function retaining () {
  var self = this;

  return function () {
    console.log(self);
  };
}

retaining()();
// <- Window
 

Unless you really want to use both the parent's this and the current this values, for some reason I prefer to use the.bind function. This can be used to specify the this of the parent scope to the child scope.

 


function bound () {
  return function () {
    console.log(this);
  }.bind(this);
}

bound()();
// <- Window


Related articles: