4

I've been working a lot lately on making cleaner Javascript code, and using objects with prototypes etc. But I'm confused on some points...

function TimeCard(){
    this.date               = new Date();
    this.pay_period_begin   = null;
    this.pay_period_end     = null; 
}

Here is my timecard object with some initial values. I have a bunch of functions that I've written and more to come that are part of that timecard and, if I understand correctly, they will be prototype functions. Here is some of what I have so far:

TimeCard.prototype = {         
    init : function(){
        this.pay_period_begin   = $("#pay_period_begin");
        this.pay_period_end     = $("#pay_period_end");
    },
    getTimeCardData : function(){
          //ajax request
    },
    selectAll : function(){
        this.getTimeCardData();
    }
    ...
};

My problem is that when I try to call this.getTimeCardData() it says that my object has no such method. I can obviously access the other variables because they are declared in my constructor, but I don't understand how prototype scopes I guess. So far I have gotten around this by using tc.getTimeCardData() instead of this.getTimeCardData(), with tc being the instance of my object declared outside - var tc = new TimeCard();. I'm sure that that's not the correct way to go about this, but what is?

2
  • 2
    can you show us the function where you call this.getTimeCardData() please ? Commented Mar 3, 2014 at 10:19
  • Yeah, it's already in the code shown under the selectAll function. Commented Mar 3, 2014 at 16:51

1 Answer 1

8

My problem is that when I try to call this.getTimeCardData() it says that my object has no such method.

It sounds like this is no longer referring to your instance. You'll have to show us the actual call for us to be sure, but in JavaScript, this is set primarily by how a function is called, not where it's defined, and so it's fairly easy for this to end up being something different.

Here's a hypothetical example:

TimeCard.prototype = {
    // ...
    doSomething: function() {
        // here, `this` probably refers to the timecard
        someArray.forEach(function() {
            this.getTimeCardData(); // <=== Problem, `this` has changed
        });
    }
    // ...
};

If I call this.doSomething(); on a TimeCard object, within the call this will refer to the timecard. But within the forEach callback, this will no longer refer to the timecard. The same sort of thign happens with all kinds of callbacks; ajax, etc.

To work around it, you can remember this to a variable:

TimeCard.prototype = {
    // ...
    doSomething: function() {
        var thisCard = this;
        someArray.forEach(function() {
            thisCard.getTimeCardData(); // <=== Problem
        });
    }
    // ...
};

There are also various other ways to work around it, depending on your specific situation. For instance, you have selectAll calling getTimeCardData. But suppose selectAll is called with the wrong this value? In your comment, you said you were doing it like this:

$('#container').on('click', '#selectAll', tc.selectAll);

That means that when selectAll is called, this will refer to the DOM element, not to your object.

You have three options in that specific situation:

  1. Since you're using jQuery, you can use $.proxy, which accepts a function and a value to use as this, and returns a new function that, when called, will call the original with this set to the desired value:

    $('#container').on('click', '#selectAll', $.proxy(tc.selectAll, tc));
    
  2. Use ES5's Function#bind, which does the same thing. Note that IE8 and earlier don't have it unless you include an "ES5 shim" (hence my noting $.proxy above; you know you have that):

    $('#container').on('click', '#selectAll', tc.selectAll.bind(tc));
    
  3. Use a closure (don't let the name bother you, closures are not complicated): More (on my blog):

    $('#container').on('click', '#selectAll', function() {
        tc.selectAll();
    });
    

In all of the above, you'll lose the benefit of this referring to the DOM element. In that particular case, you probably don't care, but if you did, you can get it from the event object's currentTarget property. For instance, this calls tc.selectAll with this referring to tc and passing in what would have been this (the DOM element you hooked the handler on) as the first argument:

$('#container').on('click', '#selectAll', function(e) {
    tc.selectAll(e.currentTarget);
});

Another, less likely, possibility relates to how you're updating TimeCard.prototype. The way you're doing it, it's possible to create objects via new TimeCard() before your code that replaces the TimeCard.prototype object runs, which means they'll have the old prototype.

In general, I strongly recommend not replacing the object automatically created for the prototype property of the constructor function. Instead, just add to the object already there, like this:

function TimeCard(){
    this.date               = new Date();
    this.pay_period_begin   = null;
    this.pay_period_end     = null; 
}
TimeCard.prototype.getTimeCardData = function(){
      //ajax request
};
// ...

Here's why: Timing. If you replace the object on the prototype property, any objects you create via new TimeCard() before you do that replacement will have the old prototype, not the new one.

I also recommend always creating these within a scoping function so you know that the declaration and the prototype additions happen at the same time:

var TimeCard = (function() {
    function TimeCard(){
        this.date               = new Date();
        this.pay_period_begin   = null;
        this.pay_period_end     = null; 
    }
    TimeCard.prototype.getTimeCardData = function(){
          //ajax request
    };
    // ...

    return TimeCard;
})();

...primarily because it prevents the timing issue.

Sign up to request clarification or add additional context in comments.

8 Comments

@thefourtheye: Thanks. It does. In fact, people do. :-) There's an RSS feed linked in the top right, but any decent reader will auto-discover if you just post the address in. Drop me a note with the problem you're having? [email protected]
epic answer just as usual
Thanks, I'm starting to understand. Although neither of those were my problem I think - the actual call I was referring to is just in the selectAll function in my prototypes. So those prototypes couldn't see each other for some reason. But I do like that last example you gave, I'll have to try that.
@Tanner: That probably pushes the question out a level: How was selectAll being called? Because if selectAll were being used as a callback (event handler, ajax handler, setTimeout callback, etc.), then during the call to selectAll, this wouldn't be pointing at the object anymore.
@Tanner: Nine times out of ten, you already have a useful context you can close over, so I tend toward that. But where you don't, I'd probably lean toward having a shim and using Function#bind. But at that point, it's basically a style thing.
|

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.