首页 > 编程语言 > 详细

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

时间:2019-07-07 22:21:41      阅读:103      评论:0      收藏:0      [点我收藏+]

《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); 
console.log(a);

参考:

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

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

原文:https://www.cnblogs.com/marvelousone/p/11147833.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!