1. 程式人生 > >了解Js中的this指向

了解Js中的this指向

理解 per pre ron document 它的 執行環境 col .sh


  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);
   }



 

了解Js中的this指向