Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

oop

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.

like image 464
fent Avatar asked Apr 18 '10 07:04

fent


People also ask

How do you call a function inside the same function?

Calling a function inside of itself is called recursion.

Can you call a function from within it?

Calling a function from within itself is called recursion and the simple answer is, yes.

Is a function contained within an object?

A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object.

How can you call a function and assign the this context to an object?

call() and . apply() methods allow you to set the context for a function.


2 Answers

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

alert(this.page());

instead of

alert(this.page);
like image 163
Darin Dimitrov Avatar answered Oct 01 '22 09:10

Darin Dimitrov


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];
  }
}
like image 44
Sky Sanders Avatar answered Oct 01 '22 08:10

Sky Sanders