js objects
DESCRIPTION
OOPs implementation in Javascript by Victor on 7 Jan 2012TRANSCRIPT
Javascript Object Oriented Programming
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.
Topics to cover
What a
Primitive data types
Undefined, Null, Boolean, Number, and String.
An object is a collection of properties Properties can either be primitive data types, other
objects, or functions
An Object
Some builtin objects Array Image Date
var Image1 = new Image();
Image1.src = "myDog.gif";
function myFunc(){
}
var myObject = new myFunc(); <br>
alert(typeof myObject); // displays "object"
Sample usage of inbuilt 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"
Some more sample usage of objects
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"
Sample for constructor
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
A Simple custom object
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
Creating objects using Literal Notation
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"
Subclasses and Superclasses