JavaScript this 關鍵字
面向物件語言中 this 表示當前物件的一個參考,在 js 中 this 不是固定不變的,它會隨著執行環境的改變而改變,不管它發生什么改變,this 的指向都永遠只能看this是誰呼叫的,而不是在哪里定義的,誰呼叫的函式,函式體里的this就指誰,
注:以下輸出沒有特殊說明的都是在瀏覽器環境下進行,
方法中的 this
當前物件中的方法,需要訪問當前物件中的屬性,this指向的是方法呼叫時.前的物件,
var student = {
sname:'LiMing',
sage:18,
speak:function(){
console.log(`I am ${this.sname}`)
}
}
student.speak(); // I am LiMing
全域單獨使用 this
全域單獨使用 this,則它指向全域物件(nodejs:Global;瀏覽器:Window),
嚴格模式和平時一樣都指向全域物件,
var that = this;
console.log(that); //Window {parent: Window, opener: Window, top: Window, length: 7, frames: Window, …}
普通函式或匿名函式自調中的this
如果一個函式呼叫時前邊沒有點,則this自動指向window,
因為既然可以不加點呼叫,說明一定屬于全域window內,我們沒有加點但是程式自動變成了window.函式呼叫,
在ES5嚴格模式下:全域方法中的this指向的是undefined,
function fun (){
console.log(this);
}
fun(); //Window {parent: Window, opener: null, top: Window, length: 4, frames: Window, …}
//------------------------------------------分割線------------------------------------------
"use strict";
function fun (){
console.log(this);
}
fun(); //undefined
建構式中的this
在建構式中的所有this都被new吸引,指向正在創建的新物件,
function Student(sname,sage){
this.tname = sname;
this.tage = sage;
}
var LiMing = new Student('LiMing',18);
console.log(LiMing); //Student {tname: "LiMing", tage: 18}
原型物件中的方法中的this
指向的是以后呼叫這個方法.前的物件
function Student(sname,sage){
this.tname = sname;
this.tage = sage;
}
Student.prototype.speak = function(){
console.log(`I am ${this.tname}`)
}
var LiMing = new Student('LiMing',18);
LiMing.speak(); //I am LiMing
事件處理函式中的this
指向當前正在觸發事件的元素
btn.onclick=function(){... } //this->btn
回呼函式:
所有回呼函式,真正被呼叫時,前邊是沒有任何"物件."前綴,所以this指向的是window(嚴格模式下指向undefined),
通常如果希望回呼函式中的this不指window,而是跟外部的this保持一致,都要改為箭頭函式
setTimeout(function(){ this... });
arr.forEach(function(){ this... })
arr.map(function(){ this... })
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/80179.html
標籤:其他
上一篇:最近很多在成都軟體園上班的程式員反映外賣被偷,小偷終于抓到了
下一篇:DOM獲取頁面元素
