Skip to content

Instantly share code, notes, and snippets.

@jbman
Created March 7, 2014 09:23
Show Gist options
  • Save jbman/9408295 to your computer and use it in GitHub Desktop.
Save jbman/9408295 to your computer and use it in GitHub Desktop.
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