javascript在对象方法中传递此内容

use*_*553 1 javascript object this

这段代码有效,但我的问题是我不明白其目的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);
};
Run Code Online (Sandbox Code Playgroud)

}

Jon*_*ski 5

该值this关键字是联系在一起的function内到如何使用它的function被调用.

这包括两者letSpin()function传递给他们的简短匿名setTimeout().并且,匿名function者不会仅通过其展示位置自动继承或共享该thisletSpin().

因此,您必须使用其他名称捕获变量中的值.

var that = this;
Run Code Online (Sandbox Code Playgroud)

或者,绑定function,以便在调用时使用特定值.

setTimeout(function(){
    this.letSpin();
}.bind(this), 20);
Run Code Online (Sandbox Code Playgroud)

并且,使用bind,您也可以在没有匿名的情况下传递方法function.

setTimeout(this.letSpin.bind(this), 20);
Run Code Online (Sandbox Code Playgroud)

  • @ user308553如果在调用`function`时没有指定`this`的值,则默认值可以是全局对象,即浏览器中的`window`.注意:在严格模式下,默认值是"undefined". (2认同)