Helvdan
Helvdan

Reputation: 436

Phantomjs javascript inheritance misunderstanding

I have following files:

run.js

var cat = require('./animal/cat').create('Tom');
console.log( cat.petName );
console.log( cat.paws );
cat.voice();

animal.js

function animal(){
   this.paws = 4;
}

exports.create = function(){
    return new animal();
}

animal/cat.js

function cat( name ){
    this.petName = name
}

cat.voice = function(){
    console.log('myouu');
}

exports.create = function( name ){
    cat.prototype = require('../animal').create();
    return new cat( name );
}

When I console log the properties of cat class -- everything works just fine. Prompt prints:
Tom
4
Which means that cat yet inherits from animal. But when it comes to calling the method, following error occurs:
TypeError: 'undefined' is not a constructor (evaluating 'cat.voice()') run.js:4 in global code

I just can't comprehend what is the matter. Can anybody explain error?

Upvotes: 0

Views: 86

Answers (1)

slebetman
slebetman

Reputation: 113866

The voice function is a method of the cat() constructor, not the cat object (returned by the constructor). In other languages this is called the class method or static method.

To create a method for the cat object you need to add it to the prototype:

cat.prototype.voice = function(){
    console.log('myouu');
}

But beware, in your cat create function you then overwrite the prototype. So doing this:

exports.create = function( name ){
    cat.prototype = require('../animal').create();
    return new cat( name );
}

will delete the voice method if defined like the example I show above. The correct way to do this is that you need to inherit before declaring additional methods:

cat.prototype = require('../animal').create();
cat.prototype.voice = function(){
    console.log('myouu');
}

exports.create = function( name ){
    return new cat( name );
}

Upvotes: 2

Related Questions