[英]Array.prototype.map(callback, thisArg), second argument ignored
[英]'thisArg' parameter in Array.prototype.map
關於Array.prototype.map
mdn文檔如下所示
arr.map(callback[, thisArg])
如果提供thisArg參數來映射,它將用作回調的this值。 否則,未定義的值將用作此值。 回調最終可觀察到的this值是根據用於確定函數所看到的this的常規規則確定的。
this
值( undefined
是什么,還是由常規規則確定的另一個值是什么?
另外,在類中使用Array.map
的回調時, this
Array.map
undefined
。
class Sample {
constructor() {
this.list = [1, 2, 3];
}
mapList() {
this.list.map(function(x) {
console.log(this);
});
}
}
const obj = new Sample();
obj.mapList(); // `this` is undefined
但是在功能中使用時是窗口。 為什么this
在兩種情況下是相同的,盡管不同thisArgs
價值?
function Sample() {
this.list = [1, 2, 3];
}
Sample.prototype.mapList = function() {
return this.list.map(function(x) {
console.log(this);
});
}
const obj = new Sample();
obj.mapList(); // `this` is window(global object)
我知道這是SO中經常問到的問題,有些用戶會重復檢查該問題,但是由於我的理解不清,我不得不問這個問題。
我只是想知道,為什么this
在使用類,而不是關於解決方案(上面的代碼是未定義的bind
, arrow funtion
的東西)。 誰能幫我?
從MDN
類聲明和類表達式的主體以嚴格模式執行,即構造函數,靜態方法和原型方法,getter和setter函數均以嚴格模式執行。
在嚴格模式下,如果未指定,則未定義。
...以此形式傳遞給嚴格模式下的函數的值不會強制成為對象(也稱為“裝箱”)...因此,對於嚴格模式函數,指定的此值不會裝箱到對象中,如果未指定,這將是不確定的
如果在第二個示例中添加"use strict"
,則它也將是undefined
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.