这段代码有效,但我的问题是我不明白var that = this
. 为什么我需要这样引用它才能将它传递给 setInterval。我在http://www.sitepoint.com/what-is-this-in-javascript/中读到了“this” ,但它并没有真正回答我的问题
我的 JavaScript 代码
function spinClass(imageSource, height, width, forward, el){
this.src = imageSource;
this.spinFoward = forward;
this.element = document.getElementById(el);
this.height = height;
this.width = width;
this.d = 0;
var img = document.createElement("img");
img.setAttribute('src', this.src);
img.setAttribute('height', this.height);
img.setAttribute('width', this.width);
this.element.appendChild(img);
this.letSpin = function letSpin(){
//alert(this.d);
var that = this;
img.style.transform = "rotate(" + this.d + "deg)";
img.style.WebkitTransform= "rotate(" + this.d + "deg)";
img.style.MozTransform= "rotate(" + this.d + "deg)";
img.style.msTransform= "rotate(" + this.d + "deg)";
img.style.OTransform= "rotate(" + this.d + "deg)";
//alert(this.spinFoward);
if (this.spinFoward == true){
this.d++;
}else{
this.d--;
}
setInterval(function(){that.letSpin();}, 20);
};
}