2017-10-09 59 views
0

我正在讀一本書的JavaScript,發現有關如何使用arr.find(callback[, thisArg])的Javascript Array.prototype.find第二個參數thisArg不工作

class Person { 
    constructor(name) { 
     this.name = name; 
     this.id = Person.nextId++; 
    } 
} 

Person.nextId = 0; 

const jamie = new Person("Jamie"), 
     juliet = new Person("Juliet"), 
     peter = new Person("Peter"), 
     jay = new Person("Jay"); 
const arr = [jamie, juliet, peter, jay]; 

// option 2: using "this" arg: 
arr.find(p => p.id === this.id, juliet); // returns juliet object 

我不能得到期望的結果此代碼。 find()每次返回undefined

回答

1

您正在使用arrow函數,該函數保留詞法作用域。箭頭函數中的this變量表示window,而不是您已通過的參數juliet

要糾正這種情況,您可以簡單地使用function來創建新範圍,並通過juliet作爲this

class Person { 
 
    constructor(name) { 
 
     this.name = name; 
 
     this.id = Person.nextId++; 
 
    } 
 
} 
 

 
Person.nextId = 0; 
 

 
const jamie = new Person("Jamie"), 
 
     juliet = new Person("Juliet"), 
 
     peter = new Person("Peter"), 
 
     jay = new Person("Jay"); 
 
const arr = [jamie, juliet, peter, jay]; 
 

 
// option 2: using "this" arg: 
 
let a = arr.find(function(p) { 
 
    return p.id === this.id; 
 
}, juliet); 
 

 
console.log(a);