Adding another prototype instance to a prototype: JavaScript

My question is simple:

How do I set up a prototype of a class that inherits from the prototype of another class?

My code below works until I try to call Pierre.mySkill (), at which point the console says the function is undefined.

My reason for this, in theory, is to be able to create Pirault instances as well as Person's instances, and be able to add to the Piraute prototype without having to add to Person's.

function Person (name, age){
    this.name = name;
    this.age = age;
}

Person.prototype.info = function(){
    console.log('I am '+this.name+' and I am '+this.age+' years old.');
};

function Pirault (){
    this.skill = arguments[2];

    Person.apply(this, arguments);
}

Pirault.prototype.mySkill = function(){
    console.log('My skill is '+this.skill);
}

Pirault.prototype = Object.create(Person.prototype);
Pirault.prototype.constructor = Pirault;

var Pierre = new Pirault('Pierre', 30, 'Programming');

      

+3


source to share


2 answers


Organize your code so that all prototypes are defined after the prototype object is created. For example:

Pirault.prototype = Object.create(Person.prototype);
Pirault.prototype.constructor = Pirault;

Pirault.prototype.mySkill = function(){
    console.log('My skill is '+this.skill);
}

      



Demo... However, you define the method correctly on the prototype, but then lose it when the object (created Object.create

) becomes new Pirault.prototype

.

+2


source


As an alternative approach, you don't need constructors for this. All you need in modern browsers are objects and Object.create

:



var Person = {
  info: function() {
    console.log('I am '+ this.name +'and I am '+ this.age +' years old.')
  }
}

var Pirault = Object.create(Person)
Pirault.mySkill = function() {
  console.log('My skill is '+ this.skill)
}

var pierre = Object.create(Pirault)
pierre.name = 'Pierre'
pierre.age = 30
pierre.skill = 'Programming'

pierre.mySkill() //=> My skill is Programming

console.log(Pirault.isPrototypeOf(pierre)) //=> true
console.log(Person.isPrototypeOf(pierre)) //=> true

      

+2


source







All Articles