Created
August 4, 2015 14:12
-
-
Save stevecass/8001cb860bed34b61ed6 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="https://code.jquery.com/jquery-1.11.3.js"></script> | |
</head> | |
<body id="body"> | |
<button>Click me and watch the console</button> | |
<script> | |
function f() { | |
console.log('this in f', this); | |
console.log('arguments in f', arguments); | |
}; | |
$(document).ready(function(){ | |
$('button').on('click', function(event){ | |
console.log('this in handler', this); // this here will be the clicked button | |
f.call(document, event, 1, 2); // 'this' inside f will be document | |
f(event, 1,2); // 'this' inside f will be window - the default global object (because we didn't bind anything) | |
f.apply(document.getElementById('body'), [event, 1, 2]); // 'this' inside f will be body - supplied by the "apply" call | |
//We can create a new function from f with "this" bound to a specific object | |
var f2 = f.bind(document, 1,2,3,4,5); | |
f2(6); //in f2 this will be document and args will be [1,2,3,4,5,6] | |
f2.call(window, 'Called with call'); // in f2 this will be document - despite the f2.call here. The bind in function creation "wins" | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment