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>
What you want to do here is make an object named
Areawith the methods you described assigned to it. The easiest and cleanest way to do this would be like so:You can now use
Area.square()andArea.rectangle()as you described.