简体   繁体   English

定义jQuery函数时出现的问题

[英]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()

fiddle here 在这里摆弄

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

You can check out this link 您可以查看此链接

Here is the code: 这是代码:

var global = {};

global.sayHello = function (x){
    //do your code here
      console.log('Hello ' + x );  
};
global.sayHello('Kevin');
user = new function(){
   var private_variable;
   function private_method(){}

   this.global_variable = '';
   this.global_method = function(){};
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM