bind() VS apply() and call()
by Adambasszer
HTML
<p id="console"></p>
JavaScript
var obj = {
x: 81,
getX: function() {
console.log(this.x)
return this.x;
}
};
document.getElementById('console').innerHTML += 'obj.getX(): ' + obj.getX() + '<br/>'; //81
function globalFunction() {
console.log(this);
}
globalFunction(); //you can see it in your console (Chrome: CTRL + SHIFT + J)
var otherObj = {
x: 99
};
document.getElementById('console').innerHTML += 'obj.getX.call(otherObj): ' + obj.getX.call(otherObj) + '<br/>'; //99
document.getElementById('console').innerHTML += 'obj.getX.apply(otherObj): ' + obj.getX.apply(otherObj) + '<br/>'; //99
var myGetXFunction = obj.getX.bind(otherObj); //returns a function
document.getElementById('console').innerHTML += 'myGetXFunction(): ' + myGetXFunction(); //99