gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 15:57:48 26 4
gpt4 key购买 nike

我是 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com