tags:

views:

51

answers:

3

I have the following Javascript code

add_num = {
  f: function(html, num) {
    alert(this.page);
  },

  page : function() {
    return parseInt(this.gup('page'));
  },

  gup : function(name) {
    name = name.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');
    var regex = new RegExp('[\\?&]'+name+'=([^&#]*)');
    var results = regex.exec(window.location.href);
    if(results == null)
      return '';
    else
      return results[1];
  }
}

But when I call add_num.f() what I get from alert() is the actual code of page. That is, it returns

function() {
    return parseInt(this.gup('page'));
  }

I was expecting a numeric value and not any code at all.

+3  A: 

You are alerting the function itself, not the result of executing it. You should do this:

alert(this.page());
maid450
+2  A: 

That's because you need to call the page function:

alert(this.page());

instead of

alert(this.page);
Darin Dimitrov
A: 

The reason is that a literal is not a function, thus has no (visible) constructor so 'this' is going to refer to the calling object.

Of course, this is not true if you use assign this literal to the prototype of a function, but i am guessing this is not the case here.

Also, Darin is correct, you are returning the function, not executing it.

Just refer to the object explicitly, e.g. add_num.page().

add_num = {
  f: function(html, num) {
    alert(add_num.page());
  },

  page : function() {
    return parseInt(add_num.gup('page'));
  },

  gup : function(name) {
    name = name.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');
    var regex = new RegExp('[\\?&]'+name+'=([^&#]*)');
    var results = regex.exec(window.location.href);
    if(results == null)
      return '';
    else
      return results[1];
  }
}
Sky Sanders