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>
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With