Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript "Static Object" or Library

I'm not sure if I'm using the right terminology as I'm fairly new to Object Oriented Programming. I can make "traditional objects" in the following way:

(New File: Person.js)

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

And then to use it in the main file I have to type:

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

in order to use it. You have to create an instance of the object to use its functions.

What I want to create is something I believe is called a "static object" at least in Java or perhaps a libary. I'm thinking of something similar to use the built in Math functions. I can type

Math.sin(3.14);

without having to do something like:

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

Effectively, I want a library, but I don't know how to set it up

(File: mathlib.js)

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

and then in the main file:

mathlib.printStuff();

This gives an error of: TypeError: mathlib.printStuff is not a function

Not sure of where I'm going wrong.. (I am including the file, in the same way as before)

like image 584
ryanmattscott Avatar asked Mar 15 '23 19:03

ryanmattscott


1 Answers

What you're looking for is called the Module Pattern in javascript. It's the js equivalent of a utility class in Java. It looks like this 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;
        }
    }
}());

Then somewhere else in your code you can do the following:

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

You just have to make sure to include the file in the html, typically before the script that uses it.

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

There are ways to extend a module and/or make the code more readable. Just search for "javascript module pattern", but the above code should get you off to a good start.

like image 76
cutmancometh Avatar answered Mar 23 '23 22:03

cutmancometh