JS: Using apply / bind / bindAll
by kyllle
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
SCSS
* {
-webkit-font-smoothing: antialiased;
}
body {
padding: 5%;
}
Babel + JSX
console.clear();
// http://blog.bigbinary.com/2011/08/18/understanding-bind-and-bindall-in-backbone.html
function Developer(skill) {
console.log('skill', this);
this.skill = skill;
this.says = function() {
console.log('skill.says', this);
document.body.innerHTML = '<h1>' + this.skill + ' FTW!! </h1>';
}
}
var developer = new Developer('Javascript');
// Invoking says() returns developer.says will work
developer.says();
var anotherDeveloper = new Developer('Python');
var func = anotherDeveloper.says;
// Just want to get a hold of the says function returns Uncaught TypeError: Cannot read property 'skill' of undefined when called. `this` now references the window
// func();
// We can fix this by using apply or call
// func.apply(anotherDeveloper);
// func.call(anotherDeveloper);
// But binding would be cleaner
var func = _.bind(anotherDeveloper.says, anotherDeveloper);
//func()
// Or bindAll
_.bindAll(anotherDeveloper, 'says');
var func = anotherDeveloper.says;
func();