Saturday, April 20, 2013
Javascript: Object-Oriented Programming Basics
Alright, so now we can finally learn the basics of OOP! The first thing I'm going to introduce is a class. When you make a constructor, you are actually defining a new class! A class can be thought of as a type, or a category of objects -- remember numbers and strings? Those are types too!
/* take a look at the example below, jenny and alex are two separate objects, but they both belong to the class Person */
function Person(name, age) {
this.name = name;
this.age = age;
};
var jenny = new Person("Jenny", 18);
var alex = new Person("Alex", 13);
A prototype keeps track of what a given class can or cannot do. Javascript automatically defines the prototype for class with a constructor.
// for example, this dog constructor ensures that the dog prototype has a breed property
function Dog (breed) {
this.breed = breed;
};
Classes are really useful because they tell us helpful information about objects. You can actually think of an object as a particular instance of a class. Look at our Person class. We know that any Person will have a name and age because they are in they are in the constructor. Let's create a function like printPersonName--this will take a Person as an argument and print out their name.
// recall our Person class
function Person(name, age) {
this.name = name;
this.age = age;
};
// a function that prints out the name of any given person
function printPersonName(p) {
console.log(p.name);
};
var jenny = new Person("Jenny", 18);
printPersonName(jenny);
If you want to add a method to a class such that all members of the class can use it, we use the following syntax to extend the prototype:
className.prototype.newMethod =
function() {
statements;
};
// here's another example using the dog class:
function Dog (breed) {
this.breed = breed;
};
// here we make fifi and teach her how to bark
var fifi = new Dog("pomeranian");
Dog.prototype.bark = function() {
console.log("Arf!");
};
fifi.bark();
// here we make maya
var maya = new Dog("Pug");
maya.bark();
P.S. I created a youtube channel where I'll be uploading vlogs and cooking videos and random miscellaneous things, so if you want to get to know me a little better, I suggest you check it out! (And subscribe!) :)
Labels:
basics,
classes,
codeacademy,
coding,
CS,
fifi,
javascript,
JS,
maya,
objects II,
OOP,
pom,
programming,
prototypes,
pug
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment