In this JavaScript Video Tutorial I will completely cover JavaScript Object Oriented Programming. If you haven’t watch part 1 of this tutorial first JavaScript Video Tutorial.
OOP in JavaScript works differently from other languages. Because JavaScript is loosely typed (datatypes don’t have to be explicitly stated) you are unable to implement certain OOP concepts in JavaScript. You can however take advantage of many of the positives obtained through the use of OOP using JavaScript.
Specifically I’ll cover the following concepts:
And, much more…
The code follows the video. Use it however you wish. If you have any questions or comments leave them below.
Code From the Video
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>JavaScript OOP Tutorial</title> </head> <body> <script language="javascript" type="text/javascript"> <!-- Hide JavaScript // Object - Stores variables and the functions needed to manipulate them in one place // Class - Defines what variables and functions each object will have // Properties - The name given to variables in objects // Methods - The name given to functions in objects // To create an object you create a function with the objects name function MyObject() {}; // To create an instance of that object var myObject = new MyObject; // Your properties are defined when you create the object using the this keyword // This is called the constructor function Animal() { // newName,newSound,newOwner,newFavFood this.name = "No Name"; // this.name = newName; this.sound = "Grrr"; this.owner = "Homeless"; this.favFood = "Anything"; } // You add methods to the class using the prototype object // You encapsulate or protect access to your properties through the use of set & get Animal.prototype.setOwner = function(newOwner) { if (typeof newOwner != 'undefined') { this.owner = newOwner; } else { document.write("Please enter a valid owner name"); } } // You can also create class methods // Animal.setOwner = function(newOwner) ... Animal.prototype.getOwner = function() { return this.owner; } Animal.prototype.setName = function(newName) { if (typeof newName != 'undefined') { this.name = newName; } else { document.write("Please enter a valid animal name"); } } Animal.prototype.getName = function() { return this.name; } Animal.prototype.setNoise = function(newNoise) { if (typeof newNoise != 'undefined') { this.sound = newNoise; } else { document.write("Please enter a valid animal sound"); } } Animal.prototype.getNoise = function() { return this.sound; } // End of animal class definition var dog = new Animal(); // var dog = new Animal("Grover"); document.write(dog.getName() + "<br />"); dog.setName("Spot"); dog.setOwner("Paul"); dog.setNoise(); document.write(dog.getName() + "<br />"); document.write(dog.getOwner() + "<br />"); document.write(dog.getNoise() + "<br />"); // Inheritance is when a new object inherits properties & methods from another function Cat() { Animal.call(this); // Tells JavaScript to execute the super classes constructor this.mode = "Happy"; } Cat.prototype = new Animal(); // Set Animal as the superclass object for Cat Cat.prototype.constructor = Cat; // Assign the right constructor to this object Cat.prototype.getMode = function() { return this.mode; } Cat.prototype.setMode = function(newMode) { if (typeof newMode != 'undefined') { this.mode = newMode; } else { document.write("Please enter a valid animal mode"); } } var sophie = new Cat; sophie.setName("Sophie"); sophie.setOwner("Derek"); sophie.setNoise("Meow"); document.write(sophie.getName() + "<br />"); document.write(sophie.getOwner() + "<br />"); document.write(sophie.getNoise() + "<br />"); document.write(sophie instanceof Cat); // Check if sophie is an object created with the Cat class // As per method overloading another OOP concept // setStuff(newName) // setStuff(newName,newSound) // setStuff(newName,newSound,newOwner) // You can check whether certain properties are defined and create method prototypes on the fly // The last function created for a given name is the function attributed to the object // Prepare for insanity (You'll never do this) /* Cat.prototype.setStuff = function(newName,newOwner,newNoise) { if ((typeof newName != 'undefined') || (typeof newOwner != 'undefined') || (typeof newNoise != 'undefined')) { Cat.prototype.setStuff = function(newName,newOwner,newNoise) { this.name = newName; this.sound = newNoise; this.owner = newOwner; } else... } */ document.write("<br />" + typeof(Cat)); // This returns function for the type document.write("<br />" + typeof(sophie)); // Because JavaScript is so loosely typed Polymorphism is possible but in ways different from every other language // doAnimalStuff(Animal) { document.write(Animal.getName() + Animal.getOwner()); } // doAnimalStuff(Cat) { document.write(Cat.getName() + Cat.getOwner()); } // Other languages force you to define the type being passed to the function // Since JS doesn't PM works but it loses what makes it special in other languages --> </script> <noscript> <h3>This site requires JavaScript</h3> </noscript> </body> </html>
Hi Sir Derek, I copy pasted the example but doesn’t work. I already changed and replaced the ” and ‘ but still no luck. I have written already the code but hard to spot the error. I hope you can send me a code and I can compare it and check over again why it’s not working. Thanks
Do you get an error? You might want to print variable changes as you step through the program with the alert function. That’s how I normally find errors in Javascript
Just send me the code Sir that would really help or you can point me where I can download the code. My email is bobby.gerez@yahoo.com. I don’t know how to print variables in OOP Sir, if you can give me a sample that would really help. Thanks.
I’ll do my best to dig them up. I’m sorry I didn’t put them in a zipped archive. I didn’t think anyone would like this tutorial 🙂
Thanks Sir, this one really helps me.
function Animal(){
this.name = “No name”;
this.sound = “Grrr”;
this.owner = “No Owner”;
}
Animal.prototype.setOwner = function(newOwner)
{
if (typeof newOwner != ‘undefined’)
{
this.owner = newOwner;
}
else
{
document.write(“Please Enter a valid Owner”);
}
}
Animal.prototype.getOwner = function()
{
return this.owner;
}
Animal.prototype.setName = function(newName)
{
if (typeof newName != ‘undefined’)
{
this.name = newName;
}
else
{
document.write(“Please Enter a valid Name”);
}
}
Animal.prototype.getName = function()
{
return this.name;
}
Animal.prototype.setNoise = function(newSound)
{
if (typeof newNoise != ‘undefined’)
{
this.sound = newNoise;
}
else
{
document.write(“Please Enter a valid Sound”);
}
}
Animal.prototype.getNoise = function()
{
return this.sound;
}
var dog = new Animal();
document.write(dog.getOwner() + “”);
document.write(dog.getName() + “”);
document.write(dog.getNoise()+ “”);
I’m glad you found it useful
Your tutorials are wonderful! thx. Can we have the code in a file ? I get unwanted characters when I just copy and paste it.
Thank you 🙂 If you do a quick find replace to change back quotes into normal quotes the code will work. Sorry about that. It is an old security system that I haven’t had time to replace.
These are great!
I also was having trouble copying the code, wound up with line numbers in the code itself.
I used info from your Regular Expressions tutorial (something else I’ve been meaning to “get around to” learning) to figure out how to use a reg. exp search/replace in my editor (Ultraedit) to remove the line numbers and cr/lf after them: search: \d{3}\r\n, replace with: nothing, replace all. Works like a charm!
There may be an easier way but this worked for me, also gives me an incentive to learn more about regular expressions. Thank you again for the great tutorials.
Thank you for the kind words 🙂 If you hold your mouse over the code 3 icons pop up. One of them is labeled view source. Click on it to get rid of the line numbers. I wish it was on there without the pause, but I’m not going to complain about a free plugin.
Thank you for stopping by my website
Derek
Hi would it not be possible to add the methods inside the Animal Object as properties of the Animal object
so something like this
function Animal(){
this.owner=”Homeless”;
this.setOwner=function(ownername){
this.owner=ownername;}
this.getOwner=function(){return this.owner;}
}
var animal=new Animal();
animal.setOwner(‘john’);
document.write(animal.getOwner());
Excellent..very useful for my work..Thanks a lot sir…
You’re very welcome 🙂
can i get an archive for download. nice work man mii from far africa. all the way down man mii see ya work so mii hala u say booba man(thumbs up in ah da area man). you some freaky genius man. haya do dat man????… you cram alla da books koh.. in ma place mii say nothing do ya man!!! mii your number 1 fan say peace. Good DJOB MONSIEUR PAPPI.. U NA BROS
Thank you very much for the kind message. It is very much appreciated. I have all the videos and links to all the code on one page here JavaScript Video Tutorial. I hope it helps 🙂
this code doesn’t work!!!
I get a blank screen in all the browsers…
WHY?
it works… found a stupid mistype!!!
I’m glad you fixed it 🙂
I noticed that with the cat object you assigned a constructor “Cat.prototype.constructor = Cat;” but with the origional animal object you did not do this assigning. Why not? The only thing I can think of is that it is set by default but got overwritten when you assigned “Cat.prototype = new Animal();”
Your videos are truly awesome. Plz provide a link to download all your java script videos. It would be very grateful.. Thankyou
Thank you 🙂 I have all my videos on Youtube. They are all 100% free. My host doesn’t allow for downloads of that size though sorry.
Hello,
your tutorials are amazing,but i don’t get this one thing here
can you please tell me why with the CAT object the GET method is before SET and in all other examples we first set the value and then get the value? Thank you
Thank you 🙂 Sorry about the confusion. getMode, and setMode are 2 functions that are called to execute. They won’t execute in that order.
thank you 🙂
You’re very welcome 🙂