this關(guān)鍵字時是函數(shù)運行時自動生成的一個內(nèi)部對象,只能在函數(shù)內(nèi)部使用,總指向調(diào)用它的對象
綁定規(guī)則
默認綁定
全局環(huán)境中定義函數(shù),內(nèi)部使用this關(guān)鍵字
var name = 'Jenny'; function person() { ? return this.name; } console.log(person()); //Jenny
上述調(diào)用函數(shù)的對象在瀏覽器中為window,所以this指向window,輸出Jenny
隱式綁定
函數(shù)可以作為某個對象的方法來調(diào)用,此時this就指向這個上級對象
function test() { console.log(this.x); } ? var obj = {}; obj.x = 1; obj.m = test; ? obj.m(); // 1
一個函數(shù)中包含多個對象,盡管函數(shù)是被最外層的對象調(diào)用,this指向的也只是上一級的對象
var o = { ? a:10, ? b:{ ? ? ? fn:function(){ ? ? ? ? ? console.log(this.a); //undefined ? ? ? } ? } } o.b.fn();
上述代碼中this指向的仍舊是b,b作用域內(nèi)沒有a的定義,所以打印undefined
記住,this指向的是最后調(diào)用它的對象
new綁定
通過構(gòu)造函數(shù)new關(guān)鍵字生成一個實例對象,this指向該實例對象
function test() { this.x = 1; } ? var obj = new test(); obj.x // 1
不過也有特殊情況
當(dāng)構(gòu)造函數(shù)返回一個簡單類型,this仍指向?qū)嵗龑ο?/p>
但當(dāng)構(gòu)造函數(shù)返回一個對象時,this指向會改變成返回的對象,如下:
function fn() ? { ? ? this.user = 'xxx'; ? ? return {}; ? } var a = new fn(); ? console.log(a.user); //undefined
手寫一個new關(guān)鍵字
function mynew(Func, ...args) { ? // 1.創(chuàng)建一個新對象 ? const obj = {} ? // 2.新對象原型指向構(gòu)造函數(shù)原型對象 ? obj.__proto__ = Func.prototype ? // 3.將構(gòu)建函數(shù)的this指向新對象 ? let result = Func.apply(obj, args) ? // 4.根據(jù)返回值判斷 ? return result instanceof Object ? result : obj }
顯示修改
apply()、call()、bind()
是函數(shù)的方法,作用時改變函數(shù)的調(diào)用對象,之前已經(jīng)講過,apply,call都是臨時一次改變,而bind則是返回一個新的函數(shù),指向為傳進來的參數(shù)。
具體見下方文章鏈接:
箭頭函數(shù)
箭頭函數(shù)在定義時就已經(jīng)確定了this的指向,且不能通過顯示修改的方式改變其this指向
const button = document.getElementById('mngb'); button.addEventListener('click', ()=> { ? console.log(this === window) // true ? this.innerHTML = 'clicked button' })
如上,該箭頭函數(shù)被定義時處于全局作用域中,所以this指向window
最后說一下綁定優(yōu)先級,文章來源:http://www.zghlxwxcb.cn/news/detail-838646.html
new綁定優(yōu)先級 > 顯示綁定優(yōu)先級 > 隱式綁定優(yōu)先級 > 默認綁定優(yōu)先級文章來源地址http://www.zghlxwxcb.cn/news/detail-838646.html
到了這里,關(guān)于JavaScript this對象的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!