理解javascript中的this關鍵字

一直以來,this關鍵字都是我的知識盲區,雖然平時一直都有用到,但是都不是很理解this的指向,今天看了一篇文章,感覺受益匪淺,所以做個記錄。參考文章地址https://www.jb51.net/article/74097.htm

 

1.首先確定它是不是用new進行調用的,如果是,那麼this就指向new出來的對象

function a(x,y) {
    this.x = x
    this.y = y
}

var b = new a(1,2)

b.x // 1
b.y // 2

這裏的this就指向new出來的b

2.如果不是new進行調用,那麼看是否用了dot點調用。(用了dot調用)

var point = { 
 x : 0, 
 y : 0, 
 moveTo : function(x, y) { 
 this.x = this.x + x; 
 this.y = this.y + y; 
 } 
};

point.moveTo(1,2)

這裏用dot調用moveTo,那麼moveTo裏面的this就指向dot之前的對象。這裏dot之前的對象就是point,所以this指向point

3.如果不是new進行調用,那麼看是否用了dot點調用(沒有用dot調用)

function func(x) { 
 this.x = x; 
 } 
func(5); //this是全局對象window,x爲全局變量
x;//x => 5

這裏是函數直接調用,那麼this就指向全局變量window,這裏的this.x實際上等於window.x

var point = { 
 x : 0, 
 y : 0, 
 moveTo : function(x, y) { 
 var that = this // 加入這句,後面的this改成that,那麼就可以把this引用指向point
 // 內部函數
 var moveX = function(x) { 
 this.x = x;//this 指向什麼?window
 }; 
 // 內部函數
 var moveY = function(y) { 
 this.y = y;//this 指向什麼?window
 }; 
  moveX(x); 
  moveY(y); 
 } 
 }; 
 point.moveTo(1,1); 
 point.x; //=>0 
 point.y; //=>0 
 x; //=>1 
 y; //=>1
之前一直不理解爲什麼這裏的this是指向window,現在一目瞭然,因爲它是函數直接調用,既不是dot調用,也不是new調用,所以這裏的this指向window。如果要讓this指向point,可以在moveTo函數裏面加入var that = this。

4.apply() 和 call() 方法裏面的this指向。

function Point(x, y){ 
 this.x = x; 
 this.y = y; 
 this.moveTo = function(x, y){ 
  this.x = x; 
   this.y = y; 
 } 
} 
 
 var p1 = new Point(0, 0); 
 var p2 = {x: 0, y: 0}; 
 p1.moveTo.apply(p2, [10, 10]);//apply實際上爲p2.moveTo(10,10)
 p2.x//10

實際上這還是dot調用,this之前dot之前的對象,這裏就是p2。

強烈建議觀看原文,原文解釋的非常詳細。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章