无尽的原型javascript函数

时间:2013-01-25 18:23:18

标签: javascript function prototype

我正在尝试创建一个无限的原型函数。这是我的尝试,这是行不通的:

function Cat(name, direction) {
this.name = name;
this.stand = {left: "images/standLeft.png", right: "images/standRight.png"};
this.walk = {left: "images/walkLeft.gif", right: "images/walkRight.gif"};
this.direction = direction;
}

Cat.prototype.walking = function() {
var myDirection = (this.direction == "right" ? "+=": "-=");
var myPosition = $("#cat").css("left");
myPosition = myPosition.substring(0, myPosition.length - 2);

var distanceLeft = myPosition;
var distanceRight = 1024 - myPosition - 173;


if(this.direction == "right") {
    var distance = distanceRight;
} else {
    var distance = distanceLeft;
}
    $("#cat img")[0].src =  this.walk[this.direction];
    $("#cat").animate({
        left: myDirection + distance
        }, (22.85 * distance), function(){
            this.direction = (this.direction == "right" ? "left": "right");
             this.walking();
        });
}

var myCat = new Cat("Izzy", "right");

我认为调用(this.walking())将使用相同的对象再次运行相同的函数,但是它会抛出错误。有什么想法或建议吗?

2 个答案:

答案 0 :(得分:1)

this会有窗口范围。

$("#cat img")[0].src =  this.walk[this.direction];
var that = this;
$("#cat").animate({
    left: myDirection + distance
    }, (22.85 * distance), function(){
        that.direction = (that.direction == "right" ? "left": "right");
         that.walking();
    });

答案 1 :(得分:0)

this StackOvervlow thread上查看我对JavaScript(和jQuery)中范围处理的解释。在您的情况下,您应该接受jQuery将选择this作为cat对象之外的其他内容。另请注意,jQuery适用于HTML元素,而不是cat实例,所以即使它想要它也不能设置this =你的cat对象。

您可以将功能包装在$.proxylink)中来缓解此问题,如下所示:

// This is your original handler. I made this a named function for clarity.
var animateHandler = function() {
    this.direction = (this.direction == "right" ? "left": "right");
    this.walking();
}

// Now here's your original call to animate.
$("#cat").animate(
    { left: myDirection + distance},
    (22.85 * distance),
    animateHandler
);

// Here's what you'd change it to.
$("#cat").animate(
    { left: myDirection + distance },
    (22.85 * distance),
    $.proxy(animateHandler, this)
);