Thursday, May 16, 2013

JavaScript Learning #3 - Using a Constructor Function

An object constructor function creates a kind of 'template' from which other, similar objects can be created.

Example:


function Person(personName){
this.name = personName;
this.info = "I'm a person called " + this.name;
this.showInfo = function(){
console.log(this.info);
};
}

var name = prompt("Who are you?");
person1 = new Person(name);

// add code to create another Person object called person2, again via a prompt
// You'll need code similar to the two lines above.

function Person2(personName) {
    this.name = personName;
    this.info = "I am person called "+ this.name;
    this.showInfo = function () {
      console.log(this.info);  
    };
    
}

var name2 = prompt("Who are you buddy??");
var person2 = new Person2(name2);

person1.showInfo();
person2.showInfo();


Output:


I'm a person called kondal
I am person called kolipaka

No comments:

Post a Comment