Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive prototype inheritance in nodejs / javascript

In my nodejs program, i have a module called person and it has a prototype object(about) which also has its child method (describe). I am trying to access objects properties but i am getting undefined.

Could someone correct my understanding? what i am doing wrong here?

index.js

var Person = require("./person");
var sam = new Person({name:"Sam",age:23})
sam.about.describe();

person.js

module.exports = (function() {
    var person = function(options) {
        if (options && options.name) this.name = options.name;
        if (options && options.age) this.age = options.age;
    }
    person.prototype.about = {
        describe : function(){
            console.log("I am",this.name,"and",this.age,"years old");
        }
    }
    return person;
})();

Expected output: "I am Sam and 23 years old" Actual output: "I am undefined and undefined years old"

like image 510
Sriram Avatar asked Feb 11 '26 11:02

Sriram


1 Answers

As others have said, this in your example refers to the about object, not the person instance itself.

One way to have the API you want, is to create that about namespace within the constructor, and use bind to set correct context to the describe handler.

module.exports = (function() {
    var person = function(options) {
        if (options && options.name) this.name = options.name;
        if (options && options.age) this.age = options.age;
        this.about = {
            describe: function () {
                console.log("I am",this.name,"and",this.age,"years old");
            }.bind(this)
        };
    }

    return person;
})();

This way you can simply call

var Person = require("./person");
var sam = new Person({name:"Sam",age:23})
sam.about.describe();

>>> I am Sam and 23 years old
like image 175
Martin Adámek Avatar answered Feb 13 '26 09:02

Martin Adámek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!