I am writing some Javascript for a Change Calculator exercise. One of the requirements is to use object constructors; however, I am having a lot of trouble accessing a property in my object, from within one of the object's methods.
Here is my object:
function Coin(intValue){
this.intCents = null; //The property
function setCents(intValue) { //Trying access the intCents property from within this method
/// <summary>Sets the intCents property for this object. If the given value is invalid, then the intCents property is given NaN.</summary>
/// <param name="intCents" type="Number">The new intCents value.</param>
if (isValid(intValue)) {
this.intCents = intValue; //---javascript bugs out here!---
} else {
console.error("Invalid value given to Coin Object.");
this.intCents = NaN;
}
}
setCents(intValue);
function getCents() {
/// <summary>Returns the value of intCents.</summary>
/// <returns type="Number">The intCents value.</returns>
return this.intCents;
}
}
and here is how I use my object:
var objCoin;
var calculateChange = function () {
if (objCoin != null) {
objCoin.setCents(Number.parseInt("67"));
} else {
objCoin = new Coin(Number.parseInt("67"));
}
}
I took out some unnecessary code, but overall the basic functionality goes as following: User enters a number in a textbox and then clicks a button on a webpage. The button calls calculateChange method through the onclick event.
Inside the calculateChange method where "67" is, would normally be some code to get the textbox value. To simplify the code and provide a specific example of what type of value would be passed in, I replaced it with the "67".
What is post to happen is, assuming the user enters an integer...
If my objCoin variable is not instantiated with a Coin instance, then create a new instance and pass in the user's input through the Coin's constructor. If my objCoin is instantiated, then use the setCents method to hold the user's input.
Here is an screenshot showing what is happening and where the javascript bugs out:
From my understanding, the issue appears to be with the "this" key word, as it is apparently undefined in if-statement. Despite this, I don't see anything wrong with my code.
From what I understand in my classes, this.intCents = null;
is the correct way to create a property for the Coin object, and this.intCents
would be the correct way to refer to the property from within the object regardless of where exactly in the object it is.
I tried reading up on the following questions:
'this' is undefined in JavaScript class methods seems to talk more about the new keyword and accessing properties from already created objects.
How does the "this" keyword work? had a lot of interesting example; however, I still don't see the flaw in my code.
Where am I going wrong with accessing the intCents
property?
What is this
in this scenario? (I believe it's object variable objCoin)
Programs Used:
Visual Studio 2015 Enterprise
Google Chrome and its Developer Tools