Thursday, July 11, 2019

[JavaScript][Example] Using prototype and constructor

We can use constructor to set value of an object:
<script>
var Person = function(name, age){
    this.name = name;
    this.age  = age;
}
var person1 = new Person("Ann",19);
var person2 = new Person("Fed",55);
console.log(person1.name);
console.log(person1.age);
console.log(person2.name);
console.log(person2.age);
</script>
To create methods for object, we use prototype:
Person.prototype.getName = function(){
    return this.name;
}
Person.prototype.getAge = function(){
    return this.age;
}
and you can call it by dot notation:
person1.getName()
Full code:
<script>
var Person = function(name, age){
    this.name = name;
    this.age  = age;
}
Person.prototype.getName = function(){
    return this.name;
}
Person.prototype.getAge = function(){
    return this.age;
}
var person1 = new Person("Ann",19);
var person2 = new Person("Fed",55);
console.log(person1.name);
console.log(person1.age);
console.log(person2.name);
console.log(person2.age);
console.log(person1.getName());
console.log(person1.getAge());
</script>
Result :


No comments :

Post a Comment