I am having trouble determining what concept explains the reason as to why the value of the object's property "count" is retained in the code below.
I have read and reviewed the this and object prototype section from Getify's You Don't Know JS as well as their section explaining lexical this. However, I am not able to understand my code below. Is it lexical scoping? Or is it a this binding that allows the value of count to retained?
Below is the example code:
var obj = {
count: 0,
method: function() {
console.log("in method: " + this.count)
return this.count++;
},
}
// here is where I have issue, when the method is invoked as a function
for (var i = 0; i<10; i++) {
console.log(obj.method()) // invoked as a function
}
// I've left this small block in for convenience
// I have no trouble with understanding why this block outputs what it outputs
for (var i = 0; i<10; i++) {
console.log(obj.method) // "gets its value (a reference to a function) and then logs that" from TJ Crowder
}
I expect the output of the first method call to obj.method() to output
// 0
// in method 0
// 1
// in method 1
// 2
.
.
.
// 10
// in method 10
I have no problem with what is output. My question again is, Is it lexical scoping? Or is it a this binding that allows the value of count to retained?
Thank you for taking your time to help.
Edit 1 With help from Tj Crowder's post below, I edited code snippet to clear up mistakes because it detracted from my question.