Website Design United States, Website Design California, Website Designing United States, Website Designing California

Introduction to object orientated programming in JavaScript.

Introduction to object orientated programming in JavaScript.
Object orientated programming in JavaScript is a bit different than in other languages such as Python, C++, C# or Java. It's a useful skill to know and detailed below is one (of the quite-a-few) methods for creating the class (the information that is needed to instantiate an object).

The first example is as follows:

<html>
<script language="javascript" type="text/javascript">
function Animal(name, amountOfLegs) {
this.name = name;
this.amountOfLegs = amountOfLegs;
}
cat = Animal("cat", 4);
alert("Our animal " + cat.name + " has " + cat.amountOfLegs + " legs.");
</script>
</html>

The first line declares a function called Animal that takes two parameters - name and amountOfLegs. The next step is to set the value of those two parameters to two member variables. Member variables are variables that are individual to each object. From inside the function, member variables are distinguished by being prefixed with 'this'. We literally say "set the variables name and amountOfLegs in this object to the values of those passed in as parameters".
To create 'member functions', one uses exactly the same syntax for setting a member variable but replaces a value with a function. For example:

<html>
<script language="javascript" type="text/javascript">
function Animal(name, amountOfLegs) {
this.name = name;
this.amountOfLegs = amountOfLegs;
this.sayName = function() {
alert("I am a " + this.name);
}
}
cat = Animal("cat", 4);
alert("Our animal " + cat.name + " has " + cat.amountOfLegs + " legs.");
cat.sayName();
</script>
</html>

We'll wrap it up by declaring a function that gets called whenever we try to 'display' the object, i.e pass it to document.write or put it in a message box.

<html>
<script language="javascript" type="text/javascript">
function Animal(name, amountOfLegs) {
this.name = name;
this.amountOfLegs = amountOfLegs;
this.sayName = function() {
alert("I am a " + this.name);
}
this.toString = function() {
return "An animal called " + this.name;
}
}
cat = Animal("cat", 4);
alert("Our animal " + cat.name + " has " + cat.amountOfLegs + " legs.");
cat.sayName();
document.write(cat); // It will write the text toString() returns.
</script>
</html>

There you have a very, very basic introduction to OOP in JavaScript. A very good further resource is http://www.crockford.com/javascript/inheritance.html for a much more in-depth look at the different forms of inheritance at your disposal and such.

Author Information:

Paul...

http://

Comments:

Add your comments here.

Name

Comment

You can also send feedback to feedback@programmers-corner.com
















 


© 2008-2009 dotnet4all.com