Skip to content

Instantly share code, notes, and snippets.

@limabeans
Last active November 1, 2017 03:47
Show Gist options
  • Save limabeans/a916c7e61bb14de693bb23dd6ce96b1a to your computer and use it in GitHub Desktop.
Save limabeans/a916c7e61bb14de693bb23dd6ce96b1a to your computer and use it in GitHub Desktop.
several examples of how context in event handler function actually changes
for reference: https://stackoverflow.com/questions/5490448/how-do-i-pass-the-this-context-into-an-event-handler
ex1
<html>
<body>
<button id="but">button</button>
<script>
var but=document.getElementById('but');
function Button() {
this.init = function() {
console.log(this); // A
but.addEventListener('click', function(e) {
console.log(this); // B
this.fn(e); // fail
});
}
this.fn = function(e) {
console.log('Button fn')
}
}
var button = new Button();
button.init();
// context at A != context at B
</script>
</body>
</html>
<html>
<body>
<button id="but">button</button>
<script>
var but=document.getElementById('but');
function Button() {
this.init = function() {
var that = this;
but.addEventListener('click', function(e) {
that.fn(e); // works
});
}
this.fn = function(e) {
console.log('Button fn')
}
}
var button = new Button();
button.init();
</script>
</body>
</html>
ex2
<html>
<body>
<button id="but">button</button>
<script>
var but=document.getElementById('but');
function Button() {
this.init = function() {
but.addEventListener('click', this.fn);
// works b/c we pass in ref to this.fn directly.
}
this.fn = function(e) {
console.log('Button fn')
}
}
var button = new Button();
button.init();
</script>
</body>
</html>
ex3
<html>
<body>
<button id="but">button</button>
<script>
var but=document.getElementById('but');
function Button() {
this.init = function() {
but.addEventListener('click', (e) => this.fn(e));
// works again, arrow fn magic...
}
this.fn = function(e) {
console.log('Button fn')
}
}
var button = new Button();
button.init();
</script>
</body>
</html>
ex4
<html>
<body>
<button id="but">button</button>
<script>
var but=document.getElementById('but');
function Button() {
this.init = function() {
but.addEventListener('click', function(e) {
this.fn(e);
});
// back to failing again.
}
this.fn = function(e) {
console.log('Button fn')
}
}
var button = new Button();
button.init();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment