current position:Home>Problems and cases of JavaScript pointing to this

Problems and cases of JavaScript pointing to this

2021-08-27 00:15:58 Gentle_ Zhou

this Pointing problems are usually divided into ordinary functions this Points to the and arrow functions this Point to .

This paper focuses on describing the properties of ordinary functions this Point to the problem . The following is a direct case

    let obj = {
      name:' Xiao Xu ',
    // At this point, the method of the object is called , Then we can default to obj.func As To call , be this It points to obj.
    obj.func() // output  " Xiao Xu "
    let obj1 = obj.func
    // Directly call... By function , Then put obj1() As, because function Of this Pointing to is automatically set to... By default window
    obj1() //output " Xiaozhou "

 Copy code 

Through the above cases, we can know ,this In fact, the essence of the pointing problem is the problem of who calls the method . If funciton Is set as a property in the object , And finally through "obj.func()" Method call ,this Point to the object . If funciton It is realized and called by setting global variables , As above "obj1()" Method call , Obviously ,funciton Exposed to the global environment , Naturally at this time this The point is window.

Let's pass another interview question from Ali ( similar ) Consolidate your knowledge .

    var obj = {

    var obj1 = obj.func() //  Object calls directly  this Point to obj  Output  21
    var obj2 = obj.func
    obj2() // Function calls directly  this Point to window  Output 22

    var Obj = {
    Obj.func(obj.func) // Function calls directly  this Point to window  Output  22
    // This step will obj.func The whole of the funciton Function passed in ,fun()  amount to  function(){console.log(this.age)}()
    // So the essence is through funcion Call directly ,this Point to window.

    Obj.func = obj.func
    Obj.func() //  Object calls directly ,this Point to Obj  Output  23
 Copy code 

copyright notice
author[Gentle_ Zhou],Please bring the original link to reprint, thank you.

Random recommended