簡體   English   中英

為什么帶有“ this”的此功能不起作用? 關於“這個”及其范圍

[英]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是指windowwindow.length0

 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 / 0undefined ,而大多數其他數字/ 0Infinity (或-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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM