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.
Calling a function inside of itself is called recursion.
Calling a function from within itself is called recursion and the simple answer is, yes.
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.
call() and . apply() methods allow you to set the context for a function.
That's because you need to call the page
function:
alert(this.page());
instead of
alert(this.page);
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];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With