Created
March 7, 2014 09:23
-
-
Save jbman/9408295 to your computer and use it in GitHub Desktop.
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
class ArrowFunctionDemo { | |
private text:string; | |
constructor(message:string) | |
{ | |
this.text = message; | |
// Doesn't work | |
var b1 = this.createButton("How are you? (Function reference)"); | |
b1.onclick = this.answer; | |
// works (Store this reference as 'self') | |
var b2 = this.createButton("How are you? (self pattern)"); | |
var self = this; | |
b2.onclick = function() { self.answer() }; | |
// works (TypeScipt way) | |
var b3 = this.createButton("How are you? (TypeScript arrow function)"); | |
b3.onclick = () => { this.answer() }; | |
// works (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) | |
var b4 = this.createButton("How are you? (Function bind)"); | |
b4.onclick = this.answer.bind(this); | |
} | |
private createButton(buttonText: string) : HTMLButtonElement | |
{ | |
var button = document.createElement('button'); | |
button.textContent = buttonText; | |
document.body.appendChild(button); | |
return button; | |
} | |
private answer():void | |
{ | |
var div = document.createElement('div'); | |
div.innerHTML = this.text; | |
document.body.appendChild(div); | |
} | |
} | |
var demo = new ArrowFunctionDemo("I'm fine"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment