Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Object - Call without creating it (like Math object)

Tags:

javascript

I'm new to JavaScript objects. I want to create an object like the JavaScript Math object. But it is not working (it returns nothing).

I want to create an object called Area and give it the methods square and rectangle. I want to use it the same way the Math object is used. To find the area of a square I would do:

var squareArea = Area.square(10); // 100

I chose areas for the example because it's simple.

My script is as follows:

<script>
window.onload = function() {


    function Area() {

        function square(a) {
            area = a * a;
            return area;
        }

        function rectangle(a, b) {
            area = a * b;
            return area;    
        }

    }

    rectangleArea = Area.rectangle(10, 20);

    alert(rectangleArea);

}
</script>
like image 765
user1822824 Avatar asked Jan 18 '13 01:01

user1822824


2 Answers

This will create an object called Area with methods on it.

var Area = {
    staticMethod: function() { }
};

Unless you want Area callable, don't make it a function.

like image 66
alex Avatar answered Oct 27 '22 00:10

alex


What you want to do here is make an object named Area with the methods you described assigned to it. The easiest and cleanest way to do this would be like so:

var Area = {

    square: function(a)
    {
        return a * a;
    },

    rectangle: function(a, b)
    {
        return a * b;  
    }

};

You can now use Area.square() and Area.rectangle() as you described.

like image 39
Marty Avatar answered Oct 26 '22 22:10

Marty