fent
fent

Reputation: 18205

How do I call functions of an object inside the same object?

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.

Upvotes: 13

Views: 14046

Answers (3)

Sky Sanders
Sky Sanders

Reputation: 37074

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];
  }
}

Upvotes: 7

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

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

alert(this.page());

instead of

alert(this.page);

Upvotes: 9

maid450
maid450

Reputation: 7486

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

alert(this.page());

Upvotes: 4

Related Questions