javascript this Pointing Related Problems and Changing Methods

  • 2021-09-24 21:14:17
  • OfStack

In learning javascript, we are often confused by the pointing problem of this. Today, we will learn the pointing problem of this and the method of changing the pointing problem of this.

1. The pointing problem of 1. this

We need to understand two points before learning the pointing problem of this:

1: this always points to 1 object;

2: The direction of this depends entirely on the location of the function call;

We can understand the first point above well, because in javascript, all cuts are objects. The second point is actually easy to understand. When the position of function call is different, the objects pointed by this are different, so it can be said that the pointing of this can be dynamically transformed. Let's first look at the pointing of this through a simple example.


<script>
function fun(){
   console.log(this.name);

 }
 var change={
   name:'hello',
   f:fun
 }
 var name ='world'
 var result=change.f()//hello
 fun();//world
</script>

Through the above example, we can clearly see the change of the pointing of this. Because there is a function in the object change, this is the object outside the pointing function, so hello is output.

Presumably, after reading the above examples, everyone has a definite understanding of the dynamic pointing switching of this.

Then, next, we will make a summary of the most frequent use of this. The most common ones are the following three:

Method, event binding, constructor, timer in object

Needless to say about the first two, let's look at the this pointing problem in the timer.


var obj = {
  fun:function(){
    this ;
  }
}
​
setInterval(obj.fun,1000);   // this Point window Object 
setInterval('obj.fun()',1000); // this Point obj Object 

setInterval () is a built-in method under window object, which accepts two parameters. The first parameter allows a function or an executable JS code, and the second parameter is the time interval for executing the previous function or code;

In the code above, setInterval (obj.fun, 1000) is the fun of the obj object, Because functions in JS can be passed by reference as values, Actually, the address of this function is passed to the setInterval method as a parameter, in other words, the first parameter of setInterval accepts a function, then after 1000 milliseconds, the function runs under the window object, that is, the caller of the function has become an window object, so this points to the global window object;

The first parameter in setInterval ('obj. fun ()', 1000) is actually a piece of executable JS code passed in; After 1000 milliseconds, when the JS engine executes this code, it finds the fun function through the obj object and calls it for execution, so the running environment of the function is still in the object obj, so the this inside the function also points to the obj object;

In addition to these, we need to understand three functions that can change the direction of this, including arrow function, call () and apply ()

Arrow function: There is an official explanation. One of the reasons why the arrow function is introduced is that it is not bound to this;; In the arrow function, the this of the arrow function is set to the enclosed lexical environment, in other words, the this of the arrow function depends on the environment in which the function was created.

var globalObject = this;
var foo = (() = > this);
console.log(foo() === globalObject); // true
//Follow the code above
//Call as 1 method of an object
var obj = {foo: foo};
console.log(obj.foo() === globalObject); // true

//Try using call to set this
console.log(foo.call(obj) === globalObject); // true

//Try to set this using bind
foo = foo.bind(obj);
console.log(foo() === globalObject); // true

In any case, this of foo is set to the environment in which it was created (in the above example, the global object). The same applies to arrow functions created within other functions: The this of these arrow functions is set to that of the enclosed lexical environment.


//  Create 1 Contains bar Method's obj Object, 
// bar Return 1 Functions, 
//  This function returns this , 
//  The returned function is created as an arrow function, 
//  So its this Is permanently bound to its outer functions this . 
// bar Can be set in the call, which in turn sets the value of the return function. 
var obj = {
 bar: function() {
  var x = (() => this);
  return x;
 }
};

//  As obj Object's 1 Methods to call bar , put its this Bind to obj . 
//  Assigns a reference to the returned function to fn . 
var fn = obj.bar();

//  Direct call fn Without setting this , 
//  Usually ( That is, the arrow function is not used ) Default to global object 
//  If in strict mode; Otherwise undefined
console.log(fn() === obj); // true

//  But note that if you just quote obj The method, 
//  Without calling it 
var fn2 = obj.bar;
//  Then after calling the arrow function, this Point window Because it starts from  bar  Inherit this . 
console.log(fn2()() == window); // true

call and apply methods: Take an object as the first parameter of call or apply, and this will be bound to this parameter object


var obj = {parent:' Male '};
var parent = '28';
function child(obj){
  console.log(this.parent);
}
child(); // 28 
child.call(obj); // Male 
child.apply(obj); // Male 

Related articles: