为什么我从Find()获得“未定义”返回值使用“This”参数?

时间:2016-05-02 04:45:58

标签: javascript

我正在研究Ethan Brown的“学习JavaScript”,并且有一个例子不能正常工作,我不确定会出现什么问题。我正在处理的部分是处理使用find()方法搜索数组,而没有做我期望的特定部分涉及使用带有“this”参数的find()方法。

我希望这个调用find(),它返回“daniel”Person:

arr.find(p => p.id === daniel.id);

返回与此调用find()相同的结果,这也应该返回“daniel”Person:

arr.find(p => p.id === this.id, daniel);

相反,第一次查找调用正常,但第二次返回“未定义”。这是为什么?

以下是完整的代码示例(摘自学习JavaScript的第8章 - Ethan Brown):

*注意本书使用ES6

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

Person.nextId = 0;

const james = new Person("Jammes"),
      juliett = new Person("Juliett"),
      daniel = new Person("Daniel"),
      jay = new Person("Jay");

const arr = [james, juliett, daniel, jay];

// option 1: find daniel id by direct comparison 
// successfully returns daniel object
arr.find(p => p.id === daniel.id);

// option 2: find jay id by using "this" arg - 
// should return daniel object, instead returns undefined...
arr.find(p => p.id === this.id, daniel);

1 个答案:

答案 0 :(得分:4)

Arrow functions继承了this的词法scope in which they are created绑定。

您无法以thisbindcall更改箭头功能的apply绑定,这正是find尝试的传递手动thisArg绑定时执行。

尝试使用常规功能来记录差异。

npm install