js中this的指向問題歸納總結(jié)
前言
js中this指向問題是個老生常談的問題了,下面這篇文章再來給大家介紹下,大家可以看看,更深入的了解了解,下面話不多說了,來一起看看詳細的介紹吧
this
this:上下文,會根據(jù)執(zhí)行環(huán)境變化而發(fā)生指向的改變.
1.單獨的this,指向的是window這個對象
alert(this); // this -> window
2.全局函數(shù)中的this
function demo() {
alert(this); // this -> window
}
demo();
在嚴格模式下,this是undefined.
function demo() {
'use strict';
alert(this); // undefined
}
demo();
3.函數(shù)調(diào)用的時候,前面加上new關(guān)鍵字
所謂構(gòu)造函數(shù),就是通過這個函數(shù)生成一個新對象,這時,this就指向這個對象。
function demo() {
//alert(this); // this -> object
this.testStr = 'this is a test';
}
let a = new demo();
alert(a.testStr); // 'this is a test'
4.用call與apply的方式調(diào)用函數(shù)
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.元素綁定事件,事件觸發(fā)后,執(zhí)行的函數(shù)中的this,指向的是當前元素
window.onload = function() {
let $btn = document.getElementById('btn');
$btn.onclick = function(){
alert(this); // this -> 當前觸發(fā)
}
}
7.函數(shù)調(diào)用時如果綁定了bind,那么函數(shù)中的this指向了bind中綁定的元素
window.onload = function() {
let $btn = document.getElementById('btn');
$btn.addEventListener('click',function() {
alert(this); // window
}.bind(window))
}
8.對象中的方法,該方法被哪個對象調(diào)用了,那么方法中的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));
答案
1.console.log(a.fn());
對象調(diào)用方法,返回了一個方法。
# function() {return this.x}
2.console.log((a.fn())());
a.fn()返回的是一個函數(shù),()()這是自執(zhí)行表達式。this -> window
# 20
3.console.log(a.fn()());
a.fn()相當于在全局定義了一個函數(shù),然后再自己調(diào)用執(zhí)行。this -> window
# 20
4.console.log(a.fn()() == (a.fn())());
# true
5.console.log(a.fn().call(this));
這段代碼在全局環(huán)境中執(zhí)行,this -> window
# 20
6.console.log(a.fn().call(a));
this -> a
# 15
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
JavaScript中promise.all和promise.race的區(qū)別詳解
Promise.all和Promise.race是JavaScript的兩種Promise處理方法,Promise.all要求所有Promise對象成功完成才返回成功,若有一個失敗則整體失敗,Promise.race返回第一個完成的Promise結(jié)果,需要的朋友可以參考下2024-09-09
微信小程序?qū)崿F(xiàn)Timeline時間線效果
這篇文章主要為大家詳細介紹了微信小程序?qū)崿F(xiàn)Timeline時間線效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-05-05
elementUI 設(shè)置input的只讀或禁用的方法
這篇文章主要介紹了elementUI 設(shè)置input的只讀或禁用的方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-10-10
iframe的父子窗口之間的對象相互調(diào)用基本用法
iframe在使用時可能會涉及到父子窗口之間傳值和方法的相互調(diào)用,研究了一下其實非常簡單,就那么幾個用法而已,在此與大家分享下,感興趣的朋友可以參考下2013-09-09

