Anuj Pandey
Anuj Pandey

Reputation: 938

Nodejs util.inherits produce unexpected results

Following code always prints 3 3 where as it should be printing 2 3 anything in any suggestions as to what I am doing wrong here ? or this is expected ?

var EventEmitter = require("events").EventEmitter,
    util=require('util');
var Car=function(){
    var self=this;
    EventEmitter.call(this);
    var make=1;
    Car.prototype.getMake = function() {
        return make;
    };
    Car.prototype.setMake = function(val) {
        make=val;
        return make;
    };
}
util.inherits(Car, EventEmitter);

function Bmw(){
    Car.call(this);
}

function Merc(){
    Car.call(this);
}
util.inherits(Bmw, Car);
util.inherits(Merc, Car);

var car1=new Bmw();
car1.setMake(2);

var car2=new Merc();
car2.setMake(3);

console.log(car1.getMake(),car2.getMake());

Upvotes: 0

Views: 52

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161457

var Car = function(){
    var self=this;
    EventEmitter.call(this);
    var make=1;
    Car.prototype.getMake = function() {
        return make;
    };
    Car.prototype.setMake = function(val) {
        make=val;
        return make;
    };
};

does not make sense. Car.prototype.getMake affects every single instance of Car, so what you are basically saying is, every time a new Car() instance is created, change the getMake and setMake function on ALL instances back to 1. Then when you call setMake it changes the make value for every instance

You either need to assign them explicitly to a single instance of Car. e.g.

var Car = function(){
    EventEmitter.call(this);

    var make=1;
    this.getMake = function() {
        return make;
    };
    this.setMake = function(val) {
        make=val;
        return make;
    };
};

Or keep them on the prototype and use a different method for passing the value of make into the functions.

var Car = function(){
    var self=this;
    EventEmitter.call(this);
    this.make_ = 1;
};

Car.prototype.getMake = function() {
    return this.make_;
};
Car.prototype.setMake = function(val) {
    this.make_ = val;
    return this.make_;
};

Upvotes: 1

Related Questions