[英]Why does this function with “this” not work? About “this” and its scope
我知道以這種方式向原型添加方法並不是最好的方法,但是我只是在測試。
Array.prototype.maap = function (transform) { let mapped = []; for (let element of this) { mapped.push(transform(element)); } return mapped; } console.log([0, 2, 3].maap(n => n / this.length));
我正進入(狀態:
[NaN,Infinity,Infinity]。 我認為問題是“ this.length”。
沒錯,問題是this.length
。 麻煩的是它不在函數中 ! 它在lambda中,其作用域不是后來被其調用的數組的作用域。 因此, this
不是數組,而this.length
是實數0(0/0為NaN,2/0為無窮大,而3/0也為無窮大)。
您可以對實際值3
進行硬編碼,也可以將邏輯移入函數本身。 或者,您可以讓lambda(實際上是JavaScript中的“箭頭函數”)采用另一個參數:分母的參數。
Array.prototype.maap = function (transform) { let mapped = []; for (let element of this) { mapped.push(transform(element, this.length)); } return mapped; } console.log([0, 2, 3].maap((n, m) => n / m));
this
箭頭函數內部引用相同的this
在其包含塊。 在這里,包含塊是頂層, this
是指window
, window.length
是0
。
console.log(this === window); console.log(window.length);
因此,您的代碼等效於:
Array.prototype.maap = function(transform) { let mapped = []; for (let element of this) { mapped.push(transform(element)); } return mapped; } console.log(this.length); console.log([0, 2, 3].maap(n => n / 0));
0 / 0
是undefined
,而大多數其他數字/ 0
是Infinity
(或-Infinity
)。
如果要使用this
模擬Array.prototype.map
的行為,則傳遞給maap
的第二個參數應該是使用this
方法調用回調的this
值:
Array.prototype.maap = function(transform, thisVal) { let mapped = []; for (let element of this) { mapped.push(transform.call(thisVal, element)); } return mapped; } const arr = [0, 2, 3]; console.log(arr.maap( function(n){ return n / this.length; }, arr ));
我認為問題出在箭頭函數(參數transform
)上,是的, this.length
是直接相關的問題,深入一點,這是關於箭頭函數的問題,
箭頭函數沒有它自己的
this
。 使用封閉詞匯范圍的this
值;
簡而言之,其中箭頭功能定義了this
點的位置。
因此,對於您的代碼,您傳入的參數為n => n / this.length
,並且在window
環境中的console.log
函數中定義。 所以真正的問題是:
transf = (n) => {
console.log(this); // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
return n / this.length
}
console.log([0, 2, 3].maap(transf));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.