箭头函数和this

76 阅读1分钟

1 匿名函数 箭头函数一般用于匿名函数的声明。在js中,传统声明形式的匿名函数中的this,指向全局;箭头函数中的this,指向它所在的封闭的上下文。function printSong() { console.log("Oops - The Global Object"); } const jukebox = { songs: [ { title: "Wanna Be Startin' Somethin'", artist: "Michael Jackson", }, { title: "Superstar", artist: "Madonna", }, ], printSong: function (song) { console.log(song.title + " - " + song. artist); }, printSongs: function () { // thisbound to the object (OK) this.songs.forEach(function (song) { //this bound to global object (bad) this.printSong(song); }); }, } jukebox.printSongs();

2 自定义组建函数 在使用React Class创建的组件中,创建自定义组建函数时,使用传统的function需要在constructor()中调用bind()进行绑定,这样function中的this才能指向这个组件本身,使用箭头函数创建的自定义组建函数就不需要这一步。