Change JavaScript Function Context
by Wentz Wu
HTML
<h1><a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Function/bind" target="_blank">Cnage the function context</a></h1>
<div id="result"></div>
JavaScript
this.x = 9; // this refers to global "window" object here in the browser
var module = {
x: 81,
getX: function() { return this.x; }
};
print(module.getX()); // 81
var retrieveX = module.getX;
print(retrieveX());
// returns 9 - The function gets invoked at the global scope
// Create a new function with 'this' bound to module
// New programmers might confuse the
// global var x with module's property x
var boundGetX = retrieveX.bind(module);
print(boundGetX()); // 81
function print(msg) {
var result = document.getElementById("result");
result.innerText += (msg + "\r");
}