This question already has an answer here:
这个问题在这里已有答案:
- JavaScript - Owner of “this” 5 answers
JavaScript - “this”的所有者5个答案
I have this function right here which takes the parts of my object and illuminates them successively with a delay (it switches the opacity of an element to 1 and then switches the previous element opacity to 0 to illuminate them successively).
我在这里有这个功能,它接受我的对象的部分并连续照亮它们延迟(它将元素的不透明度切换为1,然后将前一个元素的不透明度切换为0以连续照亮它们)。
The problem is that I cannot use the this keyword to access the parent objects parts in the illuminateInternal
function.
问题是我无法使用this关键字访问illuminateInternal函数中的父对象部分。
This hinders any possible reuse of my object since I will have maleBackNoZoom and maleBackFullZoom objects.
这阻碍了我的对象的任何可能的重用,因为我将有maleBackNoZoom和maleBackFullZoom对象。
I don't want to change the variable names of the illuminateInternal
function when I re-use my object so I would like to use something like the this
keyword in the illuminateInternal
function as well.
当我重新使用我的对象时,我不想更改illuminateInternal函数的变量名,所以我想在illuminateInternal函数中使用类似this关键字的东西。
maleBackNoZoom = {
parts:{
armsRight: findItemById("29") ,
armsLeft: findItemById("28"),
legsRight: findItemById("21"),
legsLeft: findItemById("22"),
back: findItemById("24"),
buttocks: findItemById("23"),
neck: findItemById("26"),
head: findItemById("27")
},
illuminate: function() {
var propertiesToIlluminate = [], prop, illuminateInternal, i = 0, delay = 200, intervalId;
for (prop in this.parts) {
propertiesToIlluminate.push(prop);
}
illuminateInternal = function () {
var property = propertiesToIlluminate[i];
var previousProperty = propertiesToIlluminate[i-1];
maleBackNoZoom.parts[property].opacity = 1;
console.log(previousProperty);
if (typeof previousProperty !== 'undefined'){
maleBackNoZoom.parts[previousProperty].opacity = 0;
}
paper.view.update();
i++;
if (i === propertiesToIlluminate.length) {
maleBackNoZoom.parts[property].opacity = 0;
clearInterval(intervalId);
setInterval(function(){paper.view.update()},delay);
}
};
intervalId = setInterval(illuminateInternal, delay);
}
}
1 个解决方案
#1
0
You can define local variable inside illuminate
method which will store reference to its object. And then you can use it as alias of this
.
您可以在illuminate方法中定义局部变量,该方法将存储对象的引用。然后你可以用它作为别名。
var self = this;
illuminateInternal = function () {
..
self.parts[property].opacity = 1;
}
#1
0
You can define local variable inside illuminate
method which will store reference to its object. And then you can use it as alias of this
.
您可以在illuminate方法中定义局部变量,该方法将存储对象的引用。然后你可以用它作为别名。
var self = this;
illuminateInternal = function () {
..
self.parts[property].opacity = 1;
}