0

This is a question of general curiosity, I've been teaching myself Object Oriented javascript programming because I like the structure and flexibility it provides, but I have run into an issue that I'm puzzled by more than anything else. Suppose I have the following code:

function total (el,arr,i) 
{

   this.across = function(el,arr,i) {

     $(el).each(function() {
       if(!$(this).attr("id"))
          {
            //-- convert each value to a number and push to items array
            arr.push(parseFloat($(this).val()));
            i = i++;
          }
     });
    return arr;
   };
}

I can create a new instance of total and pass it my element, array, and index parameters, and then call total.across to populate my array and update the index of i like so:

$(document).ready(function (){


  var arr = [[],[],[]];
  var i = 0;
  var el = $("#hourly input");
  var t = new total(el,arr,i);
  alert(t.across());


});  

My question is, once I enter the .each method, the keyword this no longer refers to the instance of total, but now to the element passed in the .each method. How then do I push the value returned to the array passed to the original function. In this example I'm using the arr keyword but that doesn't appear to work. In the example I'm hoping to get the new

8
  • You're sure the issue isn't just your document ready function ? Commented Nov 15, 2013 at 21:46
  • Or that you're referencing the function in the alert call, not calling it ? Commented Nov 15, 2013 at 21:46
  • The actual reason the code isn't working may be that, but my question was specifically how to keep context separate and that answered my question, This is really just a test script not anything else, thanks for the heads up though. Also I didn't tag jquery because the question itself isn't jquery specific Commented Nov 15, 2013 at 21:48
  • I cleaned up the code thanks again Commented Nov 15, 2013 at 21:51
  • 1
    You're doing it completely wrong, you have to do this -> jsfiddle.net/xH6GF/1 Commented Nov 15, 2013 at 21:51

1 Answer 1

3

Assign a context variable of this:

this.across = function(el,arr,i) {
    var that = this;
        $(el).each(function() {
            console.log(that); //is "this" from before the .each
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that makes a lot of sense.
In the future it would be possible to use the .bind() method to assign a context to a function. Unfortunately it doesn't work with IE < 9, because it's part of Javascript 1.8.5 (at least not without modifying the function prototype or using a Framework like MooTools)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.