TypeError: Cannot read property 'setGear' of undefined

TypeError: Cannot read property 'setGear' of undefined
0.0 0

#1

What’s wrong with this code? Why myBike.setGear() is the the only statement which does not work ? I’m getting a TypeError.

Thank you for your explanations.

var Car = function() {
// this is a private variable
var speed = 10;

// these are public methods
this.accelerate = function(change) {
speed += change;
};

this.decelerate = function() {
speed -= 5;
};

this.getSpeed = function() {
return speed;
};
};

var Bike = function() {

// Only change code below this line.

var gear;

this.setGear = function(x){
gear = x;
};

this.getGear = function(){
return gear;
};
};

myBike.setGear(4);
myBike.setGear(3);
myBike.setGear(1);

var myCar = new Car();

var myBike = new Bike();


#2

You are getting an error because you are calling methods on myBike before assigning a value to it. If you put all this
myBike.setGear(4); myBike.setGear(3); myBike.setGear(1);
after
var myBike = new Bike();
it should work.


#3

Yep it works. thanks. what a shameful mistake.