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

首頁 > 語言 > JavaScript > 正文

基于javaScript的this指向總結

2024-05-06 15:14:03
字體:
來源:轉載
供稿:網友

在javascript中this的指向一直是前端同事的心頭病,也同時是各面試題的首選,現在我們就來總結一下js中this的指向。首先需要了解一下幾個概念:

1:全局變量默認掛載在window對象下

2:一般情況下this指向它的調用者

3:es6的箭頭函數中,this指向創建者,并非調用者

4:通過call、apply、bind可以改改變this的指向

下面我們具體分析一下

1:在函數調用時

 (非嚴格模式)

const func = function () {  console.log(this);  const func2 = function () {   console.log(this);  };  func2(); //Window }; func(); //Window

 (嚴格模式)

'use strict' const func = function () {  console.log(this);  const func2 = function () {   console.log(this);  };  func2(); //undefined }; func(); //undefined

結合第四和第一兩條規則:func這個函數是全局的,默認掛載在window對象下,this指向它的調用者即window,所以輸出window對象,但是在嚴格模式下,this不允許指向全局變量window,所以輸出為undefined(func2在函數直接調用時默認指向了全局window,其實這屬于javascript設計上的缺陷,正確的設計方式是內部函數的this 應該綁定到其外層函數對應的對象上,為了規避這一設計缺陷,聰明的 JavaScript 程序員想出了變量替代的方法,約定俗成,該變量一般被命名為 that。這種方式在接下來會講到)。

2:作為對象方法

const user = {  userName: '小張',  age: 18,  selfIntroduction: function () {   const str = '我的名字是:' + this.userName + ",年齡是:" + this.age;   console.log(str);   const loop = function () {    console.log('我的名字是:' + this.userName + ",年齡是:" + this.age);   };   loop();  //我的名字是:undefined,年齡是:undefined  } }; user.selfIntroduction(); //我的名字是:小張,年齡是:18

按照咱的第一條規則,this指向他的調用者,selfIntroduction()方法的調用者是user,所以在selfIntroduction()方法內部this指向了他的父對象即user,而loop方法輸出的為undefined的原因就是我在上面所說的javascript的設計缺陷了,在這種情況下,我們通常選擇在selfIntroduction()方法里將this緩存下來。

const user = {  userName: '小張',  age: 18,  selfIntroduction: function () {   const str = '我的名字是:' + this.userName + ",年齡是:" + this.age;   console.log(str);   const that=this;   const loop = function () {    console.log('我的名字是:' + that.userName + ",年齡是:" + that.age);   };   loop();  //我的名字是:小張,年齡是:18  } }; user.selfIntroduction(); //我的名字是:小張,年齡是:18

此時loop的this指向就理想了。

const user={  userName:'小張',  age:18,  selfIntroduction:function(){   const str='我的名字是:'+this.userName+",年齡是:"+this.age;   console.log(str);   } }; const other =user.selfIntroduction; other(); //我的名字是:undefined,年齡是:undefined const data={  userName:'小李',  age:19, }; data.selfIntroduction=user.selfIntroduction; data.selfIntroduction(); //我的名字是:小李,年齡是:19            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 宣城市| 云梦县| 通辽市| 卢氏县| 元江| 渑池县| 阜康市| 于田县| 姜堰市| 呼伦贝尔市| 新津县| 宝应县| 江山市| 石台县| 东乌| 晴隆县| 合水县| 平顶山市| 秦皇岛市| 鸡西市| 当雄县| 长泰县| 探索| 郓城县| 呼图壁县| 隆子县| 扶风县| 长治县| 定襄县| 左权县| 屏边| 鸡西市| 广南县| 浏阳市| 汝州市| 台安县| 贵港市| 夏河县| 铜川市| 四会市| 新乐市|