使用原型从构造函数引用变量

Referencing a variable from constructor function using prototype

本文关键字:引用 变量 构造函数 原型      更新时间:2023-09-26

我是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();

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
        });
    });
};