开发者

function scope in javascript with jquery

开发者 https://www.devze.com 2023-03-26 09:23 出处:网络
$.plugin = { loadedcss: [], add: function(params) { $.each(params[\"css\"], function(key,value) { // this.loadedcss error undefined
$.plugin = {

    loadedcss   : [],

    add: function(params) { 
        $.each(params["css"], function(key,value) { 
            // this.loadedcss error undefined
            this.loadedcss.push(value);
        });
    },

    end: function(){
        //console.log(this.loadedcss);
    }
};

as you can see im trying to push my new css params to loadedcss variable. and it says er开发者_开发知识库ror undefined this.loadedcss maybe there is something that i miss

$.plugin.add({
    css: ['framework.css','csstest.css']
}); 

$.plugin.add({
    css: ['framework.css','csstest.css']
}); 

    $.plugin.end();

how can we push my params['css'] to this.loadedcss ?


You could try,

$.plugin = (function(){
var methods = {
   loadedcss   : [],

    add: function(params) { 
       // IF IN ARRAY NOT LOADED THEN PUSH CSS
      if ($.inArray(params['css'],this.loadedcss) == -1) {
         // error undefined this.loadedcss
         methods.loadedcss.push(params['css']);
       };
     },
     ...
   };

return methods;
})();

It will allow you to use internal vars as well as a side affect.

Alternatively,

add: function(params) { 
    var me = this;
    $.each(params["js"], function(key,value) { 
        // this.loadedcss error undefined
        me.loadedcss.push(value);
    });
}

Will also work


Alias the this parameter to something else (self in the example below) and then use that alias instead inside your callback function.

add: function(params) { 
    var self = this;
    $.each(params["css"], function(key,value) { 
        self.loadedcss.push(value);
    });
},

You can't use this inside the callback because $.each() will have set it to the current array element's value.


$.plugin is just a an object. It should be a function in order to create a new instance of it then you can use this in its methods. You can try this now

$.plugin = {

    loadedcss   : [],

    add: function(params) { 
        $.each(params["js"], function(key,value) { 
          // this.loadedcss error undefined
          $.plugin.loadedcss.push(value);
        });
    },

    end: function(){
        //console.log(this.loadedcss);
    }
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号