JavaScript: protecting data, revealing functionality

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.

Answer №1

To achieve similar functionality to object-oriented languages in JavaScript, you can leverage closures. Here's an example:

function Probability() {
    // private field
    var _value = 0;
    
    this.getValue = function() {
        return _value;
    };

    this.setValue = function(newValue) {
       _value = newValue;
    };

    this.sameAs = function(compare) {
        return _value === compare.getValue();
    };
}

var probability = new Probability();
probability.setValue(10);

var newProbability= new Probability();
newProbability.setValue(11);

console.log(probability.sameAs(newProbability)); // false
newProbability.setValue(10);
console.log(probability.sameAs(newProbability)); // true

If you're interested in learning more about Object-oriented JavaScript, a good resource is this site.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing commas in JavaScript

Hi everyone, I'm having an issue with printing the message "Invalid password, Must Contain:". The problem I'm facing is that when I write the code in JavaScript, the comma is being interpreted as an operator instead of a regular English comma. Th ...

NodeJS making seven successful Ajax requests

I'm delving into the world of JavaScript, NodeJS, and electron with a goal to create a presenter-app for remote control over powerpoint presentations. My setup involves an electron server structured like this: const electron = require('electron ...

Struggling with running a jQuery ajax request inside a function?

Below is my code for a jQuery Change Event: $("input[name=evnt_typ]").change(function(){ var request = $.ajax({ method: "POST", url: "ajaxRequest.php", dataType: "json ...

Transform the features of a website into a sleek iOS application using Swift

Can I take an HTML website coded with JavaScript and integrate its functionality into my app using WebKit or another method? By using WebKit or WebViews, I can load an entire webpage into my app, automatically bringing along its functionality. However, i ...

The process for changing the textContent to X when an image is clicked

How can I create a function that changes the text content to 'X' when an image is clicked? I already have a function that updates the title based on the image dataset, but combining the two functions has been unsuccessful. Can someone help me con ...

What is the most efficient method for implementing absolute imports in Webpack 2?

I'm currently working on configuring Webpack for a React project and I'm looking to streamline how I import my components. Ideally, I want to import components like this: import ComponentName from "components/ComponentName" Instead of the more ...

Converting string to JSON format by splitting it based on names

I recently manipulated a string containing the values "title:artist" by utilizing the str.split method : res = song.split(":"); The resulting output is as follows: ["Ruby","Kaiser Chiefs"] Now, I am curious about how to include the name in this array f ...

What could be causing the abundance of API calls from Yandex Metrica?

In my Nextjs SPA, there is an iframe widget that is rendered using React. Inside this widget's index.html file, I have inserted the Yandex Metrica script and set up a goal tag to track user clicks on the registration button. The goal tracking is wor ...

How can you make sure that mouse events pass through the KineticJS stage?

Is it possible to have a PanoJS3 component covering the entire screen with a KineticJS stage on top, but still allow touch events to pass through the KineticJS stage to what lies beneath? I want shapes on the stage or layer to receive the touch events, wh ...

Using JavaScript within WordPress to achieve a seamless scrolling effect

I am seeking to implement a Smooth Scroll effect on my website located at . The site is built on WordPress and I am facing difficulty in connecting JavaScript/jQuery in WordPress. I have come across various WordPress plugins, but they either do not meet my ...

Retrieve the direction of panning when the panning stops with hammer.js and limit the possible

I have integrated the hammer.js library along with its jQuery plugin. I followed the documentation and used the following code to initialize it on .game-card-mobile divs: /* Creating a Hammer object for swipeable game cards */ var $gameCard = $('.gam ...

Using React with Axios to trigger several requests with a single action

Let's say a user selects a team from a dropdown menu, triggering a request to an API endpoint. const selectHomeTeamStat = evt => { const { value } = evt.target; getStats(leagueId, value, 'home'); }; In this hypothetical scen ...

Discovering the parameters at your disposal within a callback function can be easily achieved in JavaScript and MongoDB

Being new to JavaScript and web development, I've been self-studying but have encountered many roadblocks. Currently, I'm struggling with understanding functions with callback functions and their parameters. The documentation I've read so f ...

Receiving unexpected results when returning a function within a React hook

I'm currently working on developing a custom React hook that will provide users with a function to execute. This hook is designed to generate a function internally. Check out this simplified example // fetch.js import { useEffect, useState} from &qu ...

What is the best way to display a Nested JSON structure without an object key?

Need help with extracting data from two different JSON structures. The first one is straightforward, but the second is nested in multiple arrays. How can I access the content? See below for the code snippets: // First JSON { "allSuSa": [ { ...

Mysterious occurrences always seem to unfold whenever I implement passport for user authentication in my Node.js and Express applications

At first, I wrote the following code snippet to define LocalStrategy: passport.use( 'local-login', new LocalStrategy({ usernameField:'username', passwordField: 'password', passReqtoCallback: tr ...

I'm having trouble getting FlowType.js to function properly

I have added the following code just before the closing </body> tag, but unfortunately, it seems like the type is not changing as expected. I am struggling to identify what mistake I might be making. Check out FlowType.JS on GitHub View the code on ...

Hover over a ListItem

Looking for advice on how to incorporate a Mouseover feature into a Material UI ListItem from the following link: http://www.material-ui.com/#/components/list. As the "SecondaryText" is limited to 2 lines, I am exploring options to display additional data ...

Tips for syncing HTML Canvas to track the mouse's X and Y position accurately across various screen resolutions

I'm facing an issue with my canvas game where the onclick buttons are redirecting to another menu. However, when I open the Canvas on a monitor with a different resolution, all the X & Y coordinates change and nothing works as expected. Is there a wa ...

PHP enables users to look at manual values in columns and MySQL values row by row

I have created a PHP program to organize seating arrangements for an exam hall. The user manually inputs the names of the halls, which should be displayed in columns in a table. The register numbers are fetched from a MySQL database and should be displayed ...