Javascript this keyword details

  • 2020-03-30 04:11:11
  • OfStack

This points to the constructor to instantiate the object

In the previous article, we mentioned the difference between using new and not using new to call the constructor, as shown in the following example:


function Benjamin(username, sex) {
    this.username = username;
    this.sex = sex;
}
var benjamin = new Benjamin("zuojj", "male");
//Outputs: Benjamin{sex: "male",username: "zuojj"}
console.log(benjamin);
var ben = Benjamin("zhangsan", "female");
//Outputs: undefined
console.log(ben);

When the constructor is called as a normal function, it returns no value and this points to the global object. So how can we avoid problems caused by the lack of a new keyword?


function Benjamin(username, sex) {
 //Check whether "this" is a "Benjamin" object
 if(this instanceof Benjamin) {
     this.username = username;
     this.sex = sex;
 }else {
  return new Benjamin(username, sex);
 }
}
var benjamin = new Benjamin("zuojj", "male");
//Outputs: Benjamin{sex: "male",username: "zuojj"}
console.log(benjamin);
var ben = Benjamin("zhangsan", "female");
//Outputs: Benjamin {username: "zhangsan", sex: "female"}
console.log(ben);

In the above example, we first checked to see if this is an instance of Benjammin, and if not, we automatically called the constructor with new and instantiated it, which means we no longer need to worry about missing the new keyword to instantiate the constructor. Of course in this way we may develop a bad habit, how to avoid this phenomenon? We can throw an error like this:


function Benjamin(username, sex) {
 //Check whether "this" is a "Benjamin" object
 if(this instanceof Benjamin) {
     this.username = username;
     this.sex = sex;
 }else {
  // If not, throw error.
        throw new Error("`Benjamin` invoked without `new`");
 }
}

This points to the object on which the function is called

Here's an example:


var x = 10;
var obj = {
 x: 10,
 output: function() {
  //Outputs: true
  console.log(this === obj);
  return this.x;
 },
 innerobj: {
  x: 30,
  output: function() {
   //Outputs: true
   console.log(this === obj.innerobj);
   return this.x;
  }
 }
};
//Outputs: 10
console.log(obj.output());
//Outputs: 30
console.log(obj.innerobj.output());

This points to the global object

When we talked about constructors above, we also talked about the fact that when new is not applicable, this points to a global object. Let's take a look at two common examples of fallibility:


var x = 100;
var obj = {
 x: 10,
 output: function() {
  (function() {
   //Outputs: true
   console.log(this === window);
   //Outputs: Inner: 100
   console.log("Inner:" + this.x);
  })();
  
  return this.x;
 }
};
//Outputs: 10
console.log(obj.output());

When using a closure, the scope changes and this points to the window(in the browser).


var x = 100;
var obj = {
 x: 10,
 output: function() {
  return this.x;
 }
};
var output = obj.output;
//Outputs: 10
console.log(obj.output());
//Outputs: 100
console.log(output());
var obj2 = {
 x: 30,
 output: obj.output
}
//Outputs: 30
console.log(obj2.output());

This always points to the object on which the function was called.

This points to the object assigned by the apply/call() method


var x = 100;
var obj = {
 x: 10,
 output: function() {
  return this.x;
 }
};
//Outputs: 10
console.log(obj.output());
var obj2 = {
 x: 40,
 output: obj.output
}
//Outputs: 40
console.log(obj.output.call(obj2));
//Outputs: 10
console.log(obj2.output.apply(obj));

The object this points to in the callback function is the object this points to in the callback function


//<input type="text" value="3" id="txt_username">
$("#username").on("click", function() {
 console.log(this.value);
});

6. This in function.prototype.bind

The bind () method creates a new function that, when called, has its this keyword set to The value, and provided with a given sequence of The arguments preceding any provided The when The new function is called.
Example 1:


function person() {
 return this.name;
}
//Function.prototype.bind
var per = person.bind({
 name: "zuojj"
});
console.log(per);
var obj = {
 name: "Ben",
 person: person,
 per: per
};
//Outputs: Ben, zuojj
console.log(obj.person(), obj.per());

Example 2:


this.x = 9;
var module = {
  x: 81,
  getX: function() { return this.x; }
};
//Outputs: 81
console.log(module.getX());
var getX = module.getX;
//Outputs: 9, because in this case, "this" refers to the global object
console.log(getX);
// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
//Outputs: 81
console.log(boundGetX());


Related articles: