I am trying to understand the this keyword in javascript, i have read various articles about but it seems I have still some confusion.
For example let's consider the following code:
/*
* script.js
*/
var data = 'global data';
var myObj = {
data: 'object data',
scope: function() {
console.log(this.data);
}
};
myObj.scope(); // print "object data"
So in this case the invocation context of the scope() function is the object, and this is bound to the object itself.
Now let's add some html..
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="button" value="clickme" id="button">
<script src="script.js"></script>
</body>
</html>
.. and a click event listener on the button to trigger the scope() function
document.getElementById("button").addEventListener('click', myObj.scope, false);
// click on the button => print "undefined"
On the click event this refers to the button object that doesn't have a data property, so it correctly prints undefined. Now i want to fix this issue at the declaration time using the bind method (instead of call or apply). Thus I write:
/*
* script.js
*/
var data = 'global data';
var myObj = {
data: 'object data',
scope: function() {
console.log(this.data);
}.bind(this)
};
document.getElementById("button").addEventListener('click', myObj.scope, false);
myObj.scope(); // print "global data"
// click on the button => print "global data"
It seems that I am bounding to the global object (window) instead of the myObj. Why? Which is the difference between the this keyword used in the line console.log(this.data) in the first example and the one used in the line bind(this) in the last example? Should not both refer to the myObj? I am sure I have some confusion about this point, so thanks in advance for any explanation :)