0

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.

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();
2
  • 2
    var declares a local variable, that won't be available outside of the AniSize scope, you need to attach them to this. Commented Aug 3, 2013 at 0:12
  • functions defined on the .prototype play by all the same rules of variable scope. No magic I'm afraid. Commented Aug 3, 2013 at 0:13

1 Answer 1

4

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
        });
    });
};
Sign up to request clarification or add additional context in comments.

4 Comments

I wonder why a method named transition is binding handlers. I've got a feeling that OP wants to bind in the constructor, and trigger in transition. Just a thought. ...+1 though.
@CrazyTrain: Yeah, I guess the structure could be better, I would probably create an init method and attach the events in there.
I have updated the jsFiddle but its not working... & yes I should have created a better name. This is just for testing purpose.
Mmmm, you forgot var self = this;. That's half the answer. jsfiddle.net/elclanrs/KkHfB/9

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.