首页 > 技术文章 > 《JavaScript学习指南》中的一些坑

marvelousone 2019-07-07 21:06 原文

《JavaScript学习指南》中的一些坑###

最近在看到array.find()方法时,介绍在find中使用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: 
arr.find(p => p.id === this.id, juliet); // returns juliet object 

但是实际运行结果确是undefined

原因是作者在理解ES6箭头函数中的this可能有偏差。

在之前版本,this在函数中的作用域为当前函数,但是ES6中却为全局。

要想实现期望输出,则需要用ES6之前写法。

点击查看详细内容
 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); //绑定回调函数中this的值
console.log(a);

参考:

http://hk.voidcc.com/question/p-ecfidxnq-uk.html

推荐阅读