JavaScript中this的指向問題歸納總結
前言
js中this指向問題是個老生常談的問題了,下面這篇文章再來給大家介紹下,大家可以看看,更深入的瞭解瞭解,下面話不多說了,來一起看看詳細的介紹吧
this this:上下文,會根據執行環境變化而發生指向的改變.
1.單獨的this,指向的是window這個物件
alert(this); // this -> window
2.全域性函式中的this
function demo() {
alert(this); // this -> window
}
demo();
在嚴格模式下,this是undefined.
function demo() { 'use strict'; alert(this); // undefined } demo();
3.函式呼叫的時候,前面加上new關鍵字
所謂建構函式,就是通過這個函式生成一個新物件,這時,this就指向這個物件。
function demo() {
//alert(this); // this -> object
this.testStr = 'this is a test';
}
let a = new demo();
alert(a.testStr); // 'this is a test'
前端全棧學習交流圈:866109386,面向1-3經驗年前端開發人員,幫助突破技術瓶頸,提升思維能力,群內有大量PDF可供自取,更有乾貨實戰專案視訊進群免費領取。
4.用call與apply的方式呼叫函式
function demo() {
alert(this);
}
demo.call('abc'); // abc
demo.call(null); // this -> window
demo.call(undefined); // this -> window
5.定時器中的this,指向的是window
setTimeout(function() {
alert(this); // this -> window ,嚴格模式 也是指向window
},500)
6.元素繫結事件,事件觸發後,執行的函式中的this,指向的是當前元素
window.onload = function() { let $btn = document.getElementById('btn'); $btn.onclick = function(){ alert(this); // this -> 當前觸發 } }
前端全棧學習交流圈:866109386,面向1-3經驗年前端開發人員,幫助突破技術瓶頸,提升思維能力,群內有大量PDF可供自取,更有乾貨實戰專案視訊進群免費領取。
7.函式呼叫時如果綁定了bind,那麼函式中的this指向了bind中繫結的元素
window.onload = function() {
let $btn = document.getElementById('btn');
$btn.addEventListener('click',function() {
alert(this); // window
}.bind(window))
}
8.物件中的方法,該方法被哪個物件呼叫了,那麼方法中的this就指向該物件
let name = 'finget'
let obj = {
name: 'FinGet',
getName: function() {
alert(this.name);
}
}
obj.getName(); // FinGet
---------------------------分割線----------------------------
let fn = obj.getName;
fn(); //finget this -> window
騰訊筆試題
var x = 20;
var a = {
x: 15,
fn: function() {
var x = 30;
return function() {
return this.x
}
}
}
console.log(a.fn());
console.log((a.fn())());
console.log(a.fn()());
console.log(a.fn()() == (a.fn())());
console.log(a.fn().call(this));
console.log(a.fn().call(a));
前端全棧學習交流圈:866109386,面向1-3經驗年前端開發人員,幫助突破技術瓶頸,提升思維能力,群內有大量PDF可供自取,更有乾貨實戰專案視訊進群免費領取。
答案
1.console.log(a.fn()); 物件呼叫方法,返回了一個方法。
function() {return this.x}
2.console.log((a.fn())()); a.fn()返回的是一個函式,()()這是自執行表示式。this -> window
20
3.console.log(a.fn()()); a.fn()相當於在全域性定義了一個函式,然後再自己呼叫執行。this -> window
20
4.console.log(a.fn()() == (a.fn())());
true
5.console.log(a.fn().call(this)); 這段程式碼在全域性環境中執行,this -> window
20
6.console.log(a.fn().call(a)); this -> a
15