Reputation: 2248
I am new to OOP Javascript and am trying to gain understanding on how it works by creating a simple effect. The issue I am encountering is that I cannot seem to reference variables from the constructor function inside an prototype transition function. Any help on this would be great. Thanks.
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();
Upvotes: 0
Views: 121
Reputation: 94101
var
declares a local variable, that won't be available outside of the AniSize
scope, you need to attach them to this
so you can access them in the prototype. Then you'll have to cache this
so you can reference those variables inside the extra scope that the event is creating:
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
});
});
};
Upvotes: 4