0

I am trying to add prototype to already created object Instance (Person1) in this example, but it is not getting successfully added, and thereby giving error. Can someone help me out?

<html> 
<head></head>
<body>

<script>

var person = function(name, age){
this.name = name;
this.age = age; 
this.printName = function(){
    alert(this.name);
}
}
person.prototype.printAge = function(){
alert(this.age);
}

var person1 = new person("Jack", 29); 
person1.prototype.printMessage = function(){
alert("Hello Friend"); 
}

var person2 = object.create(person1);
person2.printName();
person2.printAge();
person2.printMessage();

</script>

</body>
</html> 
Deadpool
  • 7,811
  • 9
  • 44
  • 88

2 Answers2

1

The problem is that person is a function and person1 is an object. Use constructor.prototype to solve the problem.

<html> 
<head></head>
<body>

<script>

var person = function(name, age){
this.name = name;
this.age = age; 
this.printName = function(){
    alert(this.name);
}
}
person.prototype.printAge = function(){
alert(this.age);
}

var person1 = new person("Jack", 29); 
person1.constructor.prototype.printMessage = function(){
alert("Hello Friend"); 
}

var person2 = Object.create(person1);
person2.printName();
person2.printAge();
person2.printMessage();

</script>

</body>
</html>
wisn
  • 974
  • 10
  • 17
0

Only constructor functions have protoype property (functions which sets the property values via this.propertyName. Although you can use

__proto__

it is deemed inefficient.

Check this.

stackoverflow reference

Abinash Gupta
  • 321
  • 3
  • 12