[英]How do I call functions of an object inside the same object?
I have the following Javascript code 我有以下Javascript代码
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. 但是当我调用add_num.f()时,我从alert()获得的是实际的页面代码。 That is, it returns
也就是说,它返回
function() {
return parseInt(this.gup('page'));
}
I was expecting a numeric value and not any code at all. 我期待一个数值而不是任何代码。
That's because you need to call the page
function: 那是因为你需要调用
page
函数:
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. 原因是文字不是函数,因此没有(可见)构造函数,所以'this'将引用调用对象。
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. 此外,Darin是正确的,您正在返回该函数,而不是执行它。
Just refer to the object explicitly, eg add_num.page(). 只需明确引用该对象,例如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];
}
}
You are alerting the function itself, not the result of executing it. 您正在警告函数本身,而不是执行它的结果。 You should do this:
你应该做这个:
alert(this.page());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.