I've run into a - what seems - somewhat strange problem. Let's say I have a JavaScript object like this one:
var Object = {
Property1: 0,
Property2: 1,
TxtProperty: "Sample text",
Update: function () {
this.Property1++; // Doesn't work
Object.Property2++; // Does work
this.TxtProperty = "Hello world"; // Does work
$('#prop-1').text(this.Property1); // Prints NaN
$('#prop-2').text(Object.Property2); // Prints correct value
$('#txt-prop').text(this.TxtProperty); // Prints correct value
}
};
See this fiddle for a demonstration. Click 'Start' to start the timer and update the values. As you can see, using parseInt didn't help either.
I've tested this in Firefox, Chrome, and IE10. They all show the same behavior.
Why can't you reference a property with a numeric value using this from inside another property with a function value? Why does it work with non-numeric values? Is this a bug or is this intended?
This is not so much a real problem as we can simply use the parent object's name to update the numeric value, but I'm just curious as to why this is so.
thiswill refer to Window the way you use it. Not to parent object.this.TxtPropertyshouldn't work either.window.TxtPropertyproperty.Object.TxtPropertyafter that, you'll see that it didn't change.