使用原型从构造函数引用变量
Referencing a variable from constructor function using prototype
我是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
});
});
};
相关文章:
- 通过另一个变量引用变量名称,或从变量确定变量名称
- 如何使用字符串引用变量
- 具有计算名称的引用变量
- j查询使用引用变量
- 如何处理 React 0.12+ 中的组件引用变量和 props
- 引用变量,它执行函数,但是向变量中添加字符串,将函数作为字符串而不是值返回
- 在单例模式中引用变量的根父级
- 如何在 Debian 上通过 node.js 中的引用变量停止子进程
- 可以通过画布上的引用变量来单击函数
- 使用原型从构造函数引用变量
- JQuery引用变量带有选择器,数据错误
- 引用变量
- Javascript在对象内通过字符串引用变量名
- 如何在javascript中使用不同的本地名称来引用变量或属性
- 为什么以及如何在console.log中引用变量来修复我遇到的加载错误?
- (术语)如何引用变量中的变量
- Javascript:使用"模块模式"引用变量,有什么想法吗?
- 解引用变量的闭包有用吗?
- 动态引用变量(对象)
- 定义中的引用变量