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

首頁 > 語言 > JavaScript > 正文

JavaScript箭頭函數(shù)中的this詳解

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

前言

箭頭函數(shù)極大地簡化了this的取值規(guī)則。

普通函數(shù)與箭頭函數(shù)

普通函數(shù)指的是用function定義的函數(shù):

var hello = function () {console.log("Hello, Fundebug!");}

箭頭函數(shù)指的是用=>定義的函數(shù):

var hello = () => {console.log("Hello, Fundebug!");}

JavaScript箭頭函數(shù)與普通函數(shù)不只是寫法上的區(qū)別,它們還有一些微妙的不同點,其中一個不同點就是this。

箭頭函數(shù)沒有自己的this值,箭頭函數(shù)中所使用的this來自于函數(shù)作用域鏈。

這句話很簡單,不過聽著稍微有點莫名其妙,得從頭說起。

this到底是什么?

關于this的文章也夠多了,有時候越描越黑,我就不再添亂了,我只負責搬運一下MDN文檔:this,感興趣的可以仔細閱讀一下,我摘錄一些最重要的話就好了。

A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.

JavaScript是一門比較奇特的語言,它的this與其他語言不一樣,并且它的取值還取決于代碼是否為嚴格模式("use strict")。

this的值是什么?

The JavaScript context object in which the current code is executing.

this就是代碼執(zhí)行時當前的context object。

Global context

In the global execution context (outside of any function), this refers to the global object whether in strict mode or not.

代碼沒有在任何函數(shù)中執(zhí)行,而是在全局作用域中執(zhí)行時,this的值就是global對象,對于瀏覽器來說,this就是window。

這一條規(guī)則還是比較容易接受的。

Function context

Inside a function, the value of this depends on how the function is called.

函數(shù)中的this值取決于這個函數(shù)是怎樣被調(diào)用的,這一條規(guī)則就有點變態(tài)了,也是很容易出BUG的地方。

另外,this的值還與函數(shù)是否為嚴格模式("use strict")有關,這就非常的喪心病狂了...

大家如果好奇的話,出門左轉(zhuǎn)看MDN文檔,我多說無益,只說明一種簡單的情況。

As an object method

When a function is called as a method of an object, its this is set to the object the method is called on.

當函數(shù)作為對象的方法被調(diào)用時,它的this值就是該對象。

var circle = {radius: 10,getRadius() {console.log(this.radius);}};circle.getRadius(); // 打印 10

self = this?

當我們需要在對象方法中嵌套一個內(nèi)層函數(shù)時,this就會給我們帶來實際的困擾了,大家應該寫過這樣的代碼:

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

圖片精選

主站蜘蛛池模板: 丽江市| 南漳县| 乌兰察布市| 剑阁县| 彩票| 同心县| 丹东市| 龙岩市| 抚松县| 台安县| 宣武区| 额尔古纳市| 墨脱县| 洛隆县| 丁青县| 云安县| 郯城县| 赤壁市| 博乐市| 晋中市| 马龙县| 铁岭县| 永川市| 汤原县| 萨嘎县| 九龙坡区| 临洮县| 海兴县| 灯塔市| 邢台市| 大港区| 杭锦后旗| 昭平县| 青岛市| 乌拉特后旗| 吕梁市| 开封市| 南乐县| 化州市| 阿坝| 梅河口市|