Last active
March 4, 2017 22:02
-
-
Save Edudjr/50ca53dd6aad657a0ae7a7f516069ef6 to your computer and use it in GitHub Desktop.
Examples of using 'this' context inside closures in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* In this example we will examine three different ways | |
* of using 'this' context inside a closure in javascript | |
* | |
* Suppose we have a Player class in which we'll play the next | |
* song as soon as it receives an 'onended' event from the Audio object | |
*/ | |
var Player = function(){ | |
this.songList = ['path/to/audio1.mp3', 'path/to/audio2.mp3'] | |
this.currentAudio = new Audio(this.songList[0]) | |
this.play = function(index = null){ | |
//playsong | |
this.currentAudio.play() | |
} | |
this.pause = function(){ | |
//pausesong | |
this.currentAudio.pause() | |
} | |
this.next = function(){ | |
//nextsong | |
this.currentAudio.src = this.songList[1] | |
this.currentAudio.load() | |
this.currentAudio.play() | |
} | |
//Audio Events | |
/* | |
* Note that the method bellow will not work, | |
* since the 'this' context (inside the function) | |
* refers to the Audio object | |
*/ | |
this.currentAudio.onended = function(){ | |
console.log('Event: Song has ended'); | |
this.next(); | |
} | |
/* #1 Solution | |
* We will attribute a variable 'that' to the 'this' context | |
* and call next() from 'that' | |
*/ | |
let that = this | |
this.currentAudio.onended = function(){ | |
//song has ended | |
that.next(); | |
} | |
/* #2 Solution | |
* We will bind the context of the anonymous function | |
*/ | |
this.currentAudio.onended = (function(){ | |
//song has ended | |
that.next(); | |
}).bind(this) | |
/* #3 Solution | |
* We will use arrow functions. | |
* | |
* As MDN says: "An arrow function expression has a | |
* shorter syntax than a function expression and does | |
* not bind its own this, arguments, super, or new.target." | |
*/ | |
this.currentAudio.onended = () => { | |
//song has ended | |
this.next(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment