[英]Issue while defining jQuery functions
Trying to define a couple of functions like so: 尝试定义几个函数,如下所示:
user = (function() {
var friends_list = (function() {
$.get('/ajax/user/friends_list', function(data) {
......
So I can later on call them when need it like so user.friends_list()
but for now, the only thing I get is this following error: 因此,稍后我可以在需要时像
user.friends_list()
那样调用它们,但就目前而言,我唯一得到的是以下错误:
TypeError: Object function () {
var friends_list = (function() {
$.get(....
I just don't know where else to look, any suggestions? 我只是不知道还能去哪里,有什么建议吗?
You need to create user as an object, in your case the friends_list
is a closure method, it will be availble outside the function 您需要将用户创建为一个对象,在您的情况下,
friends_list
是一个关闭方法,它将在函数外部可用
user = {
friends_list : function(){
....
}
}
make a user object and not function 使用户对象而不起作用
var user = {
friends_list : function(){
$.get('/ajax/user/friends_list', function(data) {
......
}
}
and call it like.. user.friends_list()
并称它为..
user.friends_list()
You're using a closure here, so friend_list
is invisible on the outside of user
. 您在此处使用闭包,因此在
user
外部看不到friend_list
。
If you want to use closures, to hide some variables, to best way to export friend_list
would be: 如果要使用闭包来隐藏一些变量,则导出
friend_list
最佳方法是:
(function(){
var somePrivateVariable;
window.user = {};
window.user.friend_list = function() {
// make use of somePrivateVariable...
};
})();
user = function() {
this.friends_list = function() {
$.get('/ajax/user/friends_list', function(data) {
......
});
};
return this;
};
Above should also work. 以上也应该起作用。 reference http://www.w3schools.com/js/js_objects.asp
参考http://www.w3schools.com/js/js_objects.asp
user = new function(){
var private_variable;
function private_method(){}
this.global_variable = '';
this.global_method = function(){};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.