了解Js中的this指向


  Js中的
this对象是在运行时基于函数的执行环境绑定的,其中的this指向很不好理解,一不小心就用错了位置;
  this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是那个
调用它的对象。
  
  对于this指向的理解,
我分以下几种情况来说,
this的指向
1、在全局函数中,this等于window:
var name="cyp";

console.log(this);
2、当函数被用作为某个对象的方法调用时,this等于哪个对象。


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

3构造函数的时候,指向实例化对象。

 function Person(name) {
        this.name=name;
        this.showName=function () {
            console.log(this)
        }
    }
    var person1=new Person("cyp");
    var person2=new Person("LCX");
    person2.showName();

4、不过匿名函数的执行环境具有全局性,因此其this对象通常指向window。


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

5、事件中,this指向触发这个事件的对象

// html:

<input type="button" value="点击" onclick="fun()">

//  JS:

document.querySelector("input").onclick=function () {
       console.log(this);
   }


 
原文地址:https://www.cnblogs.com/yhyanjin/p/7143285.html