使用javascript访问构造函数外部的方法?

accessing methods outside the constructor using javascript?

我正在尝试使用 this 访问构造函数外部的方法,例如:

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!
       }
    }
}

但我得到的功能未在控制台上定义。

this 指的是 Car,而不是 Garage。尝试将外部 this 分配给变量:

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();
       }
    }
}