javascript - 使用原型(prototype)从构造函数引用变量

标签 javascript jquery oop prototype

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

<强> 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 以便您可以在原型(prototype)中访问它们。然后,您必须缓存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
        });
    });
};

关于javascript - 使用原型(prototype)从构造函数引用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18027925/

相关文章:

php - 什么时候在 PHP 中使用 trait 是合适的?

php - 在父方法中获取子类名称

javascript - v-tooltip 和 v-checkbox 等 Vuetify 组件未正确注册

javascript - jQuery fadeIn 动画显示数据

javascript - ng-show 改变 div 中的最小高度

javascript - 从 ajax json 请求,如何动态地将对象添加到数组中以便我可以循环遍历它们?

jQuery 添加 css 游标类型以形成提交/链接。网站性能/速度的影响?知道 "side effects"吗?

javascript - 在循环中使用逻辑运算符会导致矛盾

javascript - 如何将 css 类应用于特定表格列和行?

oop - 这个对象初始化时会发生什么?