简体   繁体   中英

How to reduce scope of inner function variables in Javascript?

So, I have this code:

var exampleModule = (function() {
  var example = {};

  var self = this;

  example.test = function() {
    this.mousedown = function (e) {
      self.x1 = e.offsetX;
      self.y1 = e.offsetY;
    };

    this.mousemove = function(e) {
      // do something with x1 and y1 and e.offsetX and e.offsetY
    };
  };
})();

I'd like to have x1 and y1 only be scoped within example.test. Is there any way to do this with this or do I have to do something like example.test.x1 for each one? Currently they are scoped to the entire exampleModule and I would like to narrow this to just example.test .

I only somewhat understand the whole self/that = this; mantra. I know that Javascript has this bug where this when in a function in a function refers to the global scope instead, but what of when there are 3 functions like in the example above? What is this equal to when nested three or four functions down?

You can use the intermediate scope you already have with the example.test() function and store the variables there:

var exampleModule = (function() {
  var example = {};

  var self = this;

  example.test = function() {
    var x1, y1;
    this.mousedown = function (e) {
      x1 = e.offsetX;
      y1 = e.offsetY;
    };

    this.mousemove = function(e) {
      // do something with x1 and y1 and e.offsetX and e.offsetY
    };
  };
})();

Note: this design pattern is often fraught with issues because this assumes you will always get a mousedown before a mousemove which is clearly not always the case. So, you will have code carefully in the mousemove handler so you are sure you are using an appropriate value that was previously set.

Separately, it doesn't look like the value of this in example.test is probably what you want it to be, but you haven't really included enough info about that part of your code for us to know what you intended.

this in Javascript is set by how a function is called and is set to a new value in every function call in ES5 (arrow functions in ES6 are an exception). So, inside of your mousedown handler, it will be set by how this method is called. There's a summary of the various ways that this is set in this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM