-4

Im trying to access a method outside of the constructor by using this for example:

var Garage = function(location){
    this.someRandomMethod = function(){
      alert("I am a method");
    }

    // car object
    var Car = function(make,model){
      this.model = model;
      this.make  = make;

      var accessRandom = function(){
         this.someRandomMethod(); // the problem!
       }
    }
}

But I am getting function is not defined on the console.

Unknown
  • 257
  • 1
  • 3
  • 10

1 Answers1

2

The this is referring to the Car, not the Garage. Try assigning the outer this to a variable:

var Garage = function(location){
    this.someRandomMethod = function(){
      alert("I am a method");
    }

    var garage = this;

    // car object
    var Car = function(make,model){
      this.model = model;
      this.make  = make;

      var accessRandom = function(){
         garage.someRandomMethod();
       }
    }
}
tckmn
  • 57,719
  • 27
  • 114
  • 156
  • *"The `this` is referring to the `Car`"* I assume you mean instance of `Car` (not the function `Car`), but even then, we don't know that. We don't know how `accessRandom` is called. – Felix Kling Jan 04 '15 at 20:14