Using JavaScript to create a "Static Object" or Library

As a newcomer to Object Oriented Programming, I'm unsure if I'm using the correct terminology. When creating "traditional objects," I typically follow this structure:

(New File: Person.js)

function Person() {
    this.name;
    this.getName = function getName(){
        return this.name;
    }    
    this.setName = function setName(name){
        this.name = name;
    }
}

To use it in the main file, I would do something like:

var myFriend = new Person();
myFriend.setName("Bob");

This requires creating an instance of the object to access its functions.

However, what I desire is akin to a "static object" found in Java or libraries. For example, with built-in Math functions, I can simply write:

Math.sin(3.14);

Without needing to instantiate an object first:

var myMath = new Math();
myMath.sin(3.14);

Ultimately, I aim for a library setup, but I'm uncertain about the process

(File: mathlib.js)

//mathlib.js
function mathlib() {
    this.printStuff = function printStuff(){
        alert("mathlib print");
    }
}

Then in the main file:

mathlib.printStuff();

Encountering an error: TypeError: mathlib.printStuff is not a function

I'm puzzled as to where my mistake lies.. (I am including the file, just as before)

Answer №1

If you're in search of the Module Pattern within javascript, look no further. It serves as the counterpart to a utility class in Java. Here's how it appears when implemented in javascript.

Utilities.js

var Utilities = (function(){
    return {  

        addTwoNumbers : function(num1, num2){
            return num1 + num2;
        },

        greatestCommonFactor : function(num1, num2){
            while(num1 != num2){
                if(num1 > num2)
                    num1 -= num2;
                else
                    num2 -= num1;
            }
            return num1;
        }
    }
}());

Subsequently in your code, utilize the following:

var sum = Utilities.addTwoNumbers(11, 17);
var gcf = Utilities.greatestCommonFactor(21, 35);

Ensure that the file is included in the html, typically preceding the script that references it.

<script src="js/Utilities.js"></script>
<script src="js/main.js"></script>

To enhance a module or improve code readability, there are methods available. Simply search for "javascript module pattern", though the above code should set you on the right track.

Answer №2

To easily create an object, you can simply define it with the desired properties.

var mathOperations = {
    printMessage: function() {
        alert("Showing math operations");
    }
}

Alternatively,

var mathOperations = {};
mathOperations.printMessage = function() {
    alert("Showing math operations");
}

Learn more about creating objects in JavaScript here!

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

Only the first element can trigger reactions in jQuery and Ajax!

I am facing an issue on this particular page where I have several forms that can be optionally submitted using ajax. The problem lies in the fact that only the first element selected by jQuery is getting executed! Below is the JavaScript code: $(function ...

Pressing a button triggers an Ajax response, but in CasperJS it results in the entire page being refreshed

Recently, I've been experimenting with CasperJS in an attempt to identify Free-Email Alias on My focus is on the input field labeled "E-Mail-Wunschname:" where I intend to input a name, click the "Prüfen" button, and then extract the suggested accou ...

How to transfer a user's comment from HTML to a C# model through a list within the MVC framework

I have been attempting various solutions, but none seem to be working. My goal is to create post and comment partial classes for a main page where end users can add comments. Currently, I am using MVC 5 and the page loads posts and previous comments. Howe ...

Is there a way to extract the MIME type from a base64 string?

My base64 String appears as "UklGRkAdEQBXQVZFZm10IBIAAAABAAEAg...". I am attempting to download this file using my browser. Therefore, I convert it to a blob with the following function: b65toBlob: function(b64Data, sliceSize = 512) { ...

The issue in jQuery arises from a syntax error within an array

Seeking assistance to identify the issue in the following code snippet: function cat_autocomplete(){ var categoryTags = ["boots>black","boots>brown>boys>blue","clothes>small_men>scarfs>blue","boots","boots>brown>boys","boots ...

Refreshing a node in Jqgrid Treegrid by updating the local source data

I have constructed a Treegrid using local data $("#historyGrid").jqGrid({ datatype: "jsonstring", datastr : treeGridObject , colNames:["Id","Channel","Current","History","Delta"], colModel:[ {name:'id', index:'Id&apo ...

JavaScript code that opens a URL in a new tab with proper formatting

I'm having trouble figuring out how to make my JavaScript open a URL in a new tab. Here is the script: function viewSource(){ var webcache = "http://webcache.googleusercontent.com/search?q=cache:"; var request = "&prmd=ivn&strip=0& ...

Is {{@index}} an even or odd number in Handlebars: A Step-by-Step Guide

I'm currently cycling through an array, and I'd like to adjust the background color of the div based on whether the current index is odd or even. Unfortunately, when I try to use {{@index}} within an if statement in Handlebars, like so: {{#each ...

javascript game for reversing an array

in case(po==true){ snake_array.reverse(); var i=0; var c=snake_array[i]; //drawing the head draw_head(c.x,c.y); for(i=1;i<snake_array.length;i++){ //drawing the body var c=snake_arr ...

unable to reset contact form functionality

I need to implement a Contact Us form on my website. The form should clear the text fields after submission and display a Thank You message. Below is the HTML code: <div class="form"> <div id="sendmessage">Your message has been sent. Thank yo ...

Adjust the output number in a JavaScript BMI calculator to the nearest whole number when using the

Hey there, I'm currently working on a beginner project and could use some assistance. My project involves creating a basic BMI calculator using metric units, but I seem to be encountering issues with rounding numbers. Here is a snippet of my code: var ...

Deactivate a form when the page loads and activate it upon clicking a button

I have a form that I want to initially disable when the page loads. I am looking to enable it only after clicking a specific button. The technologies I'm using for this are HTML and Angular. <form name="form" id="form"> <input type="text"&g ...

Receiving a console notification about a source map error

Recently, I started receiving this warning in my console: "Source map error: request failed with status 404" resource URL: map resource URL: shvl.es.js.map" Has anyone encountered this issue before? I'm unsure of what it might be? This is my webpa ...

Utilize pivot to manage user roles and permissions in ExpressJS application using Mongoose

My user schema is structured as shown below const userSchema = mongoose.Schema({ username: { type: String, required: true, }, first_name: { type: String, required: true, }, last_name: { type: Stri ...

Accessing objects within an array in JSON using React Native

I have been struggling with this issue for a while and need some help. I am attempting to access an object within an array, specifically the URL. Here are the methods I have tried: post.yoast_head_json.og_image.url post.yoast_head_json.og_image[0].url pos ...

Tips for verifying the input field with specific requirements in Angular 6

There is an input field that needs to validate text based on certain logic conditions: No spaces should be allowed in the formula. The operators (and,or) must be lowercase and enclosed in curly brackets {}. The number of opening '(&apos ...

Streaming data from MongoDB to a file using Node.js

Having recently delved into the world of javascript/node.js, I am attempting to accomplish a basic task: connect to MongoDB, convert the JSON response to CSV format, and then write it to a file. My current approach is outlined below: fs = require('fs ...

JavaScript allows for the creation of animated or timed text

Here is the code snippet I am currently working with: function list() { return "blob1<br>blob2<br>blob3"; } When I run this code, it simply displays all the text in return at once when the function is called. I am wondering if there is a ...

Utilize the camera feature within a designated div element

I'm having trouble understanding why the camera isn't showing up in the div. Am I making a mistake somewhere? <!DOCTYPE html> <html> <head> <script type="text/javascript" src="swfobject.js"></script> </head> & ...

I am having trouble starting a server on localhost with the command npm run dev

Currently, I am in the process of developing a website using react.js and tailwindcss. However, when attempting to test my progress by running the "npm run dev" command, I discovered that it is not starting a server on localhost. I am unfamiliar with this ...