如何缩小 Javascript 中的内部函数变量的范围?
How to reduce scope of inner function variables in Javascript?
所以,我有这个代码:
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
};
};
})();
我希望 x1
和 y1
仅在 example.test 范围内。有什么方法可以用 this
来做到这一点,还是我必须为每个人做类似 example.test.x1
的事情?目前它们的范围是整个 exampleModule
,我想将范围缩小到 example.test
。
整个self/that = this;
咒语我只略懂。我知道 Javascript 有这个错误,其中 this
when in a function in a function in a function refers to the global scope,但是当上面的例子中有 3 个函数时呢?向下嵌套三个或四个函数时,this
等于什么?
您可以使用 example.test()
函数已有的中间作用域并将变量存储在那里:
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
};
};
})();
注意:这种设计模式通常充满问题,因为它假设您总是在 mousemove 之前获得 mousedown,但显然情况并非总是如此。因此,您将在 mousemove 处理程序中仔细编写代码,以确保您使用的是先前设置的适当值。
另外,this
在 example.test
中的值看起来可能不是您想要的值,但您还没有真正包含关于那部分的足够信息代码让我们知道您的意图。
this
in Javascript 由调用函数的方式设置,并在 ES5 中的每个函数调用中设置为新值(ES6 中的箭头函数除外)。因此,在您的 mousedown 处理程序内部,它将通过调用此方法的方式进行设置。在 this answer 中总结了 this
的各种设置方式。
所以,我有这个代码:
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
};
};
})();
我希望 x1
和 y1
仅在 example.test 范围内。有什么方法可以用 this
来做到这一点,还是我必须为每个人做类似 example.test.x1
的事情?目前它们的范围是整个 exampleModule
,我想将范围缩小到 example.test
。
整个self/that = this;
咒语我只略懂。我知道 Javascript 有这个错误,其中 this
when in a function in a function in a function refers to the global scope,但是当上面的例子中有 3 个函数时呢?向下嵌套三个或四个函数时,this
等于什么?
您可以使用 example.test()
函数已有的中间作用域并将变量存储在那里:
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
};
};
})();
注意:这种设计模式通常充满问题,因为它假设您总是在 mousemove 之前获得 mousedown,但显然情况并非总是如此。因此,您将在 mousemove 处理程序中仔细编写代码,以确保您使用的是先前设置的适当值。
另外,this
在 example.test
中的值看起来可能不是您想要的值,但您还没有真正包含关于那部分的足够信息代码让我们知道您的意图。
this
in Javascript 由调用函数的方式设置,并在 ES5 中的每个函数调用中设置为新值(ES6 中的箭头函数除外)。因此,在您的 mousedown 处理程序内部,它将通过调用此方法的方式进行设置。在 this answer 中总结了 this
的各种设置方式。