Creating Your Own JavaScript Objects
• 3 different ways
> Create a direct instance of an object by using built-in constructor for the Object class
> Create a template (Constructor) first and then create an instance of an object from it
> Create object instance as Hash Literal
Option 1: Creating a Direct Instance of a JavaScript Object
• By invoking the built-in constructor for the Object class
personObj=new Object(); // Initially empty with no properties or methods
• Add properties to it personObj.firstname="John"; personObj.age=50;
• Add an anonymous function to the personObj
personObj.tellYourage=function(){
alert(“This age is ” + this.age);
}
// You can call then tellYourage function as following
Option 1: Creating a Direct Instance of a JavaScript Object
• Add a pre-defined function function tellYourage(){
alert(“The age is” + this.age);
}
personObj.tellYourage=tellYourage;
• Note that the following two lines of code are doing completely different things
// Set property with a function personObj.tellYourage=tellYourage;
// Set property with returned value of the function personObj.tellYourage=tellYourage();
Option 2: Creating a template of a
JavaScript Object
• The template defines the structure of a JavaScript object in the form of a function
• You can think of the template as a constructor
function Person(firstname,lastname,age,eyecolor) {
this.firstname=firstname;ths.lastname=lastname; this.age=age; this.tellYourage=function(){
alert(“This age is ” + this.age);
}
}
Option 2: Creating a template of a
JavaScript Object
• Once you have the template, you can create new instances of the object
myFather=new Person("John","Doe",50,"blue");
myMother=new Person("Sally","Rally",48,"green");
• You can add new properties and functions to new objects
myFather.newField = “some data”; myFather.myfunction = function() { alert(this["fullName"] + ” is ” + this.age);
}
Option 3: Creating JavaScript
Object as a Hash Literal
• Create personObj JavaScript object
var personObj = {firstname: "John", lastname: "Doe", age: 50,
tellYourage: function () {
alert(“The age is ” + this.age );
}
tellSomething: function(something) {
alert(something);
}
}
personObj.tellYourage();
personObj.tellSomething(“Life is good!”);SEE VIDEO
0 Responses So Far: