0

我是 OOP Javascript 的新手,我试图通过创建一个简单的效果来了解它是如何工作的。我遇到的问题是我似乎无法从原型转换函数中的构造函数引用变量。对此的任何帮助都会很棒。谢谢。

jsFiddle

function AniSize( ele, nH, nW ) {
    this.element = ele;
    var origWidth = ele.width(),
    origHeight = ele.height(),
    newHeight = nH,
    newWidth = nW;
}

AniSize.prototype.transition = function() {
    this.element.hover(function() {
        $(this).animate({
            width: newWidth, // error: newWidth is not defined
            height: newHeight // error: newHeight is not defined
        });
    }, function() {
        $(this).animate({
            width: origWidth, // error: origWidth is not defined
            height: origHeight // error: origHeight is not defined
        });
    });
};

var box = new AniSize( $('div#box'), 200, 200 );
box.transition();
4

1 回答 1

4

var声明了一个局部变量,它在范围之外不可用AniSize,您需要将它们附加到,this以便您可以在原型中访问它们。然后您必须缓存this,以便可以在事件创建的额外范围内引用这些变量:

function AniSize( ele, nH, nW ) {
    this.element = ele;
    this.origWidth = ele.width();
    // same with the others...
}

AniSize.prototype.transition = function() {
    var self = this; // cache `this`

    this.element.hover(function() {
        $(this).animate({
            width: self.newWidth,
            height: self.newHeight
        });
    }, function() {
        $(this).animate({
            width: self.origWidth,
            height: self.origHeight
        });
    });
};
于 2013-08-03T00:14:04.623 回答