国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

js中this的指向問題歸納總結(jié)

2024-05-06 15:27:42
字體:
供稿:網(wǎng)友

前言

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'); // abcdemo.call(null); // this -> windowdemo.call(undefined); // this -> window

5.定時器中的this,指向的是window

setTimeout(function() { alert(this); // this -> window ,嚴格模式 也是指向window},500)

6.元素綁定事件,事件觸發(fā)后,執(zhí)行的函數(shù)中的this,指向的是當(dāng)前元素

window.onload = function() { let $btn = document.getElementById('btn'); $btn.onclick = function(){ alert(this); // this -> 當(dāng)前觸發(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

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 南丰县| 上蔡县| 铁力市| 巴林右旗| 通山县| 苏州市| 宣武区| 志丹县| 宝丰县| 隆安县| 普定县| 蓝田县| 海宁市| 丹凤县| 宝兴县| 防城港市| 城固县| 黄浦区| 龙胜| 江安县| 平和县| 连城县| 西安市| 延川县| 太保市| 武威市| 淅川县| 玛多县| 义乌市| 河源市| 昌吉市| 沙洋县| 邻水| 莱西市| 资源县| 泰兴市| 榆中县| 和平区| 星子县| 团风县| 泰顺县|