Looking to enhance my understanding of Javascript basics in order to delve into client-side frameworks like Knockout and Angular, as well as make headway in learning Node.js.
I've selected a simple problem used in teaching C# and am now attempting to tackle it using Javascript.
The Challenge
Create probability objects with an internal value representing the likelihood percentage. For instance, a 2/5 probability would be initiated as:
var firstOne = new Probability(40); // Representing a 2/5 chance which equates to 40%
The internal state should not be directly accessible through the instance variable. The aim of the Probability function/object is to contain the ability to compare one probability against another:
var secondOne = new Probability(30);
var areTheyEqual = firstOne.SameAs(secondOne); // In this case, it will return false
In C#, this task is comparatively straightforward. The probability value is stored in a member variable with private scope, while the SameAs function has public scope. Since each instance employs the same type, Probability, C#'s scoping enables the calling member to access the passed member's private state:
// C#
public class Probability
{
private int _value;
public Probability(int percent)
{
_value = percent;
}
public bool SameAs(Probability other)
{
return this._value == other._value; // Despite being private, this works
}
}
I'm curious if achieving this level of encapsulation is possible in Javascript. Additionally, I'm wondering whether my current approach stems from a C# and object-oriented perspective, where Javascript might offer alternative solutions leveraging its functional capabilities. I welcome insights on both fronts.