【问题标题】:Referencing a variable from constructor function using prototype使用原型从构造函数引用变量
【发布时间】:2013-08-04 09:00:25
【问题描述】:

我是 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
  • .prototype 上定义的函数使用所有相同的变量范围规则。恐怕没有魔法。

标签: javascript jquery oop prototype


【解决方案1】:

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

【讨论】:

  • 我想知道为什么名为transition 的方法会绑定处理程序。我有一种感觉,OP 想在构造函数中绑定,并在transition 中触发。只是一个想法。 ...+1 不过。
  • @CrazyTrain:是的,我想结构可能会更好,我可能会创建一个init 方法并在其中附加事件。
  • 我已经更新了 jsFiddle 但它不起作用......是的,我应该创建一个更好的名字。这只是为了测试目的。
  • 嗯,你忘了var self = this;。这是答案的一半。 jsfiddle.net/elclanrs/KkHfB/9
  • 啊,我明白了!感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-10
  • 1970-01-01
  • 2012-10-27
相关资源
最近更新 更多