0

I don't do much in the ways of object-oriented Javascript so for a script I had to write I decided to take an OO approach to better learn how it works.

I have an object called Page that defines some methods, two of which define behaviors of a page using the this variable. Eg.

var app = app || {};

app.PageType = {
    FIRST : 0,
    MIDDLE : 1,
    LAST: 2
};


app.Page = function(pageId, pageType, categoryItems) {
    this.pageType = pageType;
    this.pageId = pageId;
    this.categoryItems = categoryItems;
};

app.Page.prototype = {
    constructor: app.Page,

    someMethod: function(domDiv) {

    },

    establishListeners: function() {
        $('#Page' + this.pageId + ' > .pageNavigatorLeft').on('click', app.Page.navigateLeft);
        $('#Page' + this.pageId + ' > .pageNavigatorRight').on('click', app.Page.navigateRight);
    },

    navigateLeft: function(e) {
        var newPage = $('#Page' + (this.pageId - 1));
        var oldPage = $('#Page' + this.pageId);
        oldPage.fadeOut(2000);
        newPage.fadeIn(2000);
    },

    navigateRight: function(e) {
        var newPage = $('#Page' + (this.pageId + 1));
        var oldPage = $('#Page' + this.pageId);
        oldPage.fadeOut(2000);
        newPage.fadeIn(2000);
    }
}

The code sample above shows what I am attempting to do with the establishListeners method. Clearly this doesn't work because even if I could assign the app.Page object navigate methods as Function handlers for a jQuery event, then the this variable will refer to the anonymous function and not the specific app.Page object instance that I want this function to emulate.

Could I can wrap this with an anonymous function and pass the app.Page object instance into its own method? I don't really want to define the navigation behaviors outside of the app.Page class because this goes against the OO principle of object classes defining their own behaviors.

If what I am trying to do is a limitation of Javascript then I can accept this, but I doubt that Javascript could actually be so fundamentally, intrinsically, and sickeningly limited in its OO support so I must be making a stupid mistake here.

maple_shaft
  • 10,435
  • 6
  • 46
  • 74
  • 2
    See also: [How to access the correct `this` / context inside a callback?](http://stackoverflow.com/q/20279484/218196) – Felix Kling Jun 17 '14 at 20:46
  • 1
    I like Felix's dup better, but if that doesn't answer your question then edit to clarify your point of confusion. JavaScript OO is *very* different from what you're used to, and if you attempt to treat JS objects like you would (say) Java objects you're gonna have a bad time. (this particular scenario actually makes a ton of sense to folks who've worked with C++, but I'm not sure how much overlap there is there) – Shog9 Jul 24 '14 at 15:16

0 Answers0