1. Javascript Object Oriented Programming
Topics to cover
JavaScript’s primitive data types
What an object is in JavaScript
How to create custom objects
Object with constructor
What an object’s prototype property is
The prototype property allows you to add properties and methods to an
object.
3. An Object
An object is a collection of properties
Properties can either be primitive data types, other
objects, or functions
Some builtin objects
Array
Image
Date
4. Sample usage of inbuilt objects
var Image1 = new Image();
Image1.src = "myDog.gif";
function myFunc(){
}
var myObject = new myFunc(); <br>
alert(typeof myObject); // displays "object"
5. Some more sample usage of objects
function myFunc(){
this.StringValue = "This is a String";
}
var myObject = new myFunc();
myObject.StringValue = "This is myObject's string";
var myObject2 = new myFunc();
alert(myObject.StringValue); // displays "This is myObject's string"
alert(myObject2.StringValue); // displays "This is a String"
6. Sample for constructor
function myFunc(StringValue){
this.StringValue = StringValue;
}
var myObject = new myFunc("This is myObject's string");
var myObject2 = new myFunc("This is a String");
alert(myObject.StringValue); // displays "This is myObject's string"
alert(myObject2.StringValue); // displays "This is a String"
7. A Simple custom object
function Circle(radius){
this.radius = radius;
this.getArea = function(){
return (this.radius*this.radius*3.14);
}
this.getCircumference = function(){
var diameter = this.radius*2;
var circumference = diameter*3.14;
return circumference;
}
}
var bigCircle = new Circle(100);
var smallCircle = new Circle(2);
alert(bigCircle.getArea()); // displays 31400
alert(smallCircle.getCircumference()); // displays 12.56
8. Creating objects using Literal Notation
timObject = {
property1 : "Hello",
property2 : "MmmMMm",
property3 : ["mmm", 2, 3, 6, "kkk"],
method1 : function(){alert("Method had been called" + this.property1)}
};
timObject.method1();
alert(timObject.property3[2]) // will yield 3
var circle = { x : 0, y : 0, radius: 2 } // another example
// nesting is no problem.
var rectangle = {
upperLeft : { x : 2, y : 2 },
lowerRight : { x : 4, y : 4}
}
alert(rectangle.upperLeft.x) // will yield 2
9. Subclasses and Superclasses
function superClass() {
this.supertest = superTest; //attach method superTest
}
function subClass() {
this.inheritFrom = superClass;
this.inheritFrom();
this.subtest = subTest; //attach method subTest
}
function superTest() {
return "superTest";
}
function subTest() {
return "subTest";
}
var newClass = new subClass();
alert(newClass.subtest()); // yields "subTes
alert(newClass.supertest()); // yields "superTest"