Home > Web Front-end > JS Tutorial > body text

One article to understand the this pointing problem in JavaScript

WBOY
Release: 2022-11-30 21:00:38
forward
3156 people have browsed it

This article brings you relevant knowledge about JavaScript, which mainly introduces the related issues pointed by this. This means "this, current" and is a pointer variable. It dynamically points to the running environment of the current function. Let's take a look at it. I hope it will be helpful to everyone.

One article to understand the this pointing problem in JavaScript

【Related recommendations: JavaScript video tutorial, web front-end

The concept of this:

  • In js, this means "this; current", is a pointer variable, which dynamically points to the running environment of the current function.

  • When the same function is called in different scenarios, the pointer of this may also change, but it will always point to the real caller of the function in which it is located; if there is no caller , it points to the global object window.

Ordinary function: Regarding this, whoever calls it points to whoever calls it. If there is no caller, it points to the global object window.
Arrow function: This of the arrow function points to the object used in the function scope.

1. This in the global environment points to

In the global scope, this always points to the global object window, regardless of whether it is in strict mode or not!

##congsole.log()The complete writing method is window.console.log(), window can be omitted , window called the console.log() method, so this points to window at this time.

2. This within the function

    This within the ordinary function is divided into two situations, strict mode and non-strict mode.
1. In strict mode:

Directly call the function test(), this Points to undefined,

window.test()Call function this points to window. Therefore, in strict mode, when we call the code, we must strictly write the object of the called function, and no omissions or abbreviations are allowed.

2. In non-strict mode:

In non-strict mode, pass test() and

window.test()When calling function objects, this points to window.

3. This in the object

This in the internal methods of the object points to the object that calls these methods, that is, Whoever calls it points to .

1. One-level object:

Call the

obj.skill() method, The return value is Mengya, indicating that this points to obj at this time.

2. Second-layer object:

The order of calling skill2() method is,

obj.obj2.skill2 (), the return value is Luban, indicating that this in the skill2() method points to obj2.

Summary:

  • The definition position of a function does not affect its this pointer,

    this pointer is only related to the object that calls the function.

  • For multi-level nested objects,

    the this of the internal method points to the object closest to the called function.

4. This

Arrow function: this Points to the object used in the function scope.
    Important features of the arrow function
  • :

    There is no this and arguments in the arrow function, there really is none!

    The arrow function does not have its own this pointer, it will capture the
  • outer execution environment
  • of its

    definition, and inherit it This this value, points to the object where it is currently defined. The this point of the arrow function is determined when it is defined, and will never change thereafter. Even if you use call(), apply(), bind() and other methods to change this pointer, it is not possible.

Example 1:

  • # declares the global variable Obj, and this points to the global function where the arrow function is located The object of the domain, that is, the window object.

Example 2:

  • Since the show function is an arrow function, it cannot be bound to itself Define this, so find its upper-level scope. If the parent scope is still an arrow function, look up again, layer by layer, until you reach the point of this.

  • window.show()The return value is window, so this points to window at this time;

  • window.obj.show(), obj is an object, not an arrow function, so it stops when it finds this point, and this is bound to obj. window calls obj, so this in obj also points to window.

5. This in the constructor

This in the constructor points to Example.

As can be seen from the above figure, this in the constructor points to the instance created under the constructor.

Six, this value in the prototype chain

this value is in an inheritance mechanism, still It points to the object it originally belongs to, not the object it belongs to when it is found on the prototype chain.

7. Methods to change the point of this

1. call()

  • call(a, b, c) method receives three parameters, the first one is pointed to by this, the second one, and the three are the actual parameters passed to the function , which can be any data type such as numbers, strings, arrays, etc.

Example:

//定义函数function fn(n1,n2){
   console.log(this);  
   console.log(n1,n2)}//调用call()方法fn.call();//=>this:window;let obj = {fn:fn};fn.call(obj);
   //=>this:obj;n1,n2:undefinedfn.call(1,2);//=>this: 1;n1=2,n2=undefined;fn.call(obj,1,2);//=>this: obj;n1=1,n2=2;
   //Call方法的几个特殊属性
   //非严格模式下fn.call(undefined);//this=>windowfn.call(null);//this=>window
   //严格模式下"use strict"fn.call(undefined);//this=>undefinedfn.call(null);//this=>null
Copy after login
2. apply()
  • apply(a, [b]) is basically the same as call. The only difference is the parameter passing method. apply puts the parameters that need to be passed to fn() into an array. (or array-like), although it is written as an array, it is equivalent to passing it to fn() one by one.

  • //call()的传参方式
    fn.call(obj, 1, 2);//apply()的传参方式fn.apply(obj, [1, 2]);
    Copy after login

Example:

//apply方法的使用和call方法基本相同,唯一的区别是,apply方法传参要求是数组类型的,数组内可以任意形式的数据
function fn (n1,n2){
    console.log(this);
    console.log(n1,n2)
    console.log(arguments)}let obj = {fn:fn};
    //调用apply()方法
    fn.applay(abj,[1,2]);fn.applay(abj,1,2);
    //报错
    fn.applay(abj,[11,'apply',{a:123}]);
    //注意第二个参数必须是数组,否则会报错
Copy after login
3. bind()
  • bind (a, b, c) : The syntax is exactly the same as call. The difference is whether to execute immediately or wait for execution. bind is not compatible with IE6~8

  • The only difference between bind and call is that call directly changes the direction of function test, while bindgenerates a new function test2() , this function changes the pointer.

//call()方法:改变fn中的this,并且把fn立即执行fn.call(obj, 1, 2); //bind()方法:改变fn中的this,fn并不执行fn.bind(obj, 1, 2);
Copy after login
  • Example:

    //bind和call方法调用形式类似,但是原理完全不同
    fn.call(obj,10,20);//=>fn先执行,将fn内的this指向obj,并且把参数10,20传递给fn
    
    fn.bind(obj,10,20)//bind是先将fn中的this指向obj,并且将参数10,20预先传递给fn,但是此时的fn并没有被执行,只有fn执行时this指向和传递参数才有作用
    fn.bind(obj,10,20);//=>不会有任何输出
    fn.bind(obj,10,20)();//=>调用后才会有输出
    
    //=>需求:点击box这个盒子的时候,需要执行fn,并且让fn中的this指向obj
    oBox.onclick=fn; //=>点击的时候执行了fn,但此时fn中的this是oBox
    
    oBox.onclick=fn.call(opp); //=>绑定事件的时候就已经把fn立即执行了(call本身就是立即执行函数),然后把fn执行的返回值绑定给事件
    
    oBox.onclick=fn.bind(opp);
    //=>fn.bind(opp):fn调取Function.prototype上的bind方法,执行这个/* 
     * function(){
     *     fn.call(opp);
     * }
     */
    oBox.onclick=function(){
       //=>this:oBox
        fn.call(opp);
    }
    Copy after login

    Same points:

      call, apply and bind are all public internal methods of JS functions. They all reset the this of the function and change the execution of the function.

    Difference:

      bind creates a new function, while call and aplay are used to call functions;
    • call and apply have the same function, except that the parameters provided by call for the function are listed one by one, while the parameters provided by apply for the function are an array
    [Related recommendations:

    JavaScript video tutorialwebfrontend

    The above is the detailed content of One article to understand the this pointing problem in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

  • Related labels:
    source:csdn.net
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template