Creating An Object With Methods In Java Script/CSS

Introduction

"Everything" in JavaScript is an Object may be a String, a Number, an Array, a Date...In JavaScript, an object is data, with properties and methods.

In real life object are a bike. The features of the bike include name, model, weight, color, etc. But now here we discuss about creating a object with methods

Now I will give you an example showing you how to create methods for your objects. As an example, I will create a circle as my object. The methods will be

circle_name.area()

return the area of circle(pi*r2)

circle_name.circumfrrence()

return the circumference of circle(2*pi*r)

The complete code for web page which are consist a creation a object with methods in java script as follows

<!DOCTYPE html>

<html>

<body>

 <script>

     function circle(x, y, r)
     {

        this.xcoord = x;

        this.ycoord = y;

        this.radius = r;

        this.circleArea = getArea;

        this.retCirc = function ()
        {

            return (Math.PI * this.radius * 2);

        };

        this.mvBy = mvCclBy;

    }

    function getArea()
    {

        return (Math.PI * this.radius * this.radius);

    }

    function mvCclBy(xDis, yDis)
    {

        this.xcoord += xDis;

        this.ycoord += yDis;

    }

     var testcircle = new circle(3, 4, 5);

     testcircle.mvBy(2, 3);
     window.alert(
'The area of the circle is ' + testcircle.circleArea());

    window.alert('The circumference is ' + testcircle.retCirc());

</script>

 </body>

</html>

Output

After running the above code we'll find the following output


   Clipboard02.jpg


The next output will be


    im.jpg

Ebook Download
View all
Learn
View all