Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
  <title>Events in JavaScript: Preserving callback context using bind</title>
</head>
<body>
  <button id="element">Click Me</button>
</body>
</html>
 
var element = document.getElementById('element');
var user = {
 firstname: 'Bob',
 greeting: function(){
   alert('My name is ' + this.firstname);
 }
};
// Overwrite the original function with
// a new function with its execution
// context 'bound' to the user object
user.greeting = user.greeting.bind(user);
// Add the bound function as the callback
element.addEventListener('click', user.greeting);
Output 300px

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
wilsonpagepro
0viewers