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

时间:2013-09-19 04:14:26

标签: 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);
};

}

2 个答案:

答案 0 :(得分:5)

this keyword的值与其中使用的function以及function的调用方式有关。

这包括letSpin()和传递给function的简短匿名setTimeout()。并且,匿名function不会自动继承或仅通过其展示位置与this共享letSpin()值。

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

var that = this;

或者,bind the function所以它在调用时会使用特定的值。

setTimeout(function(){
    this.letSpin();
}.bind(this), 20);

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

setTimeout(this.letSpin.bind(this), 20);

答案 1 :(得分:0)

使用此功能实例化对象:

function newClass(klass) {
    var obj = new klass;

    $.map(obj, function(value, key) {
        if (typeof  value == "function") {
            obj[key] = value.bind(obj);
        }
    });

    return obj;
}

这将自动绑定所有函数,因此您将获得习惯性OOP样式的对象, 当对象内部的方法具有其对象的上下文时。

所以你不是通过:

实例化你的对象
var obj = new spinClass();

可是:

var obj = newClass(spinClass);
相关问题