我如何从上层作用域访问变量- javascript

How can i access vars from upper scope - javascript

本文关键字:访问 变量 javascript 作用域      更新时间:2023-09-26

我有一个问题。我怎样才能从原型扩展访问我在特斯拉模型中的变量?

还是我的插件模式错了?

我想把我的应用程序的不同区域分开,而不是把它们都放在一个大文件中

var TeslaModelS = function () {
    this.numWheels = 4;
    this.manufacturer = 'Tesla';
    this.make = 'Model S';
    this.Drive.pressGasPedal();
}
TeslaModelS.prototype = function () {
    var _this = this;
    var Drive = {
        go: function () {
          // HOW CAN I GET RED AND WRITE ACCESS TO MY VARS IN TeslaModelS ??
            console.log(_this.numWheels)
        },
        stop: function () {
        }
    }
    return {
        Drive: {
            pressBrakePedal: Drive.stop,
            pressGasPedal: Drive.go
        }
    }
}();
var i = new TeslaModelS();

对于您创建的结构,您不能。我建议使用更正常的结构:

// The constructor function
var TeslaModelS = function() {
  this.numWheels = 4;
  this.manufacturer = 'Tesla';
  this.make = 'Model S';
  this.pressGasPedal();
};
TeslaModelS.prototype.pressGasPedal = function() {
  console.log(this.numWheels);
};
TeslaModelS.prototype.pressBrakePedal = function() {
};
var i = new TeslaModelS();

但是如果你不想,如果你真的想要那个Drive对象,你需要为每个实例在一个不同的Drive对象上创建这些函数的绑定版本:

// The functions you'll bind each time
var Drive = {
  go: function() {
    console.log(this.numWheels)
  },
  stop: function() {}
};
// The constructor function
var TeslaModelS = function() {
  this.numWheels = 4;
  this.manufacturer = 'Tesla';
  this.make = 'Model S';
  // Create a Drive object for this instance with the functions bound
  // to `this`
  this.Drive = {
    pressGasPedal: Drive.go.bind(this),
    pressBrakePedal: Drive.stop.bind(this)
  };
  this.Drive.pressGasPedal();
}
var i = new TeslaModelS();