开发者

$.plugin.function and scoping in jquery?

im a php guy, right now im learning on making my first plugin

heres what im upto

$.plugin.method({ 
    test: 'helloworld'
});

$.plugin.method({ 
    test: 'another helloworld'
})  

heres my function or class ?

// class ?
jquery.plugin = function(){
    // variables
    var test = [];

    // function ?
    var method = function(params){
        test[] = params['test']
    }
    console.log(test)
}

what im expecting

test = ['helloworld','another helloworld']

can we do that in javascript ? a开发者_开发百科m i getting it right ?

thanks!


In your example you made plugin a function, but in the first snippet you are calling $.plugin.method() and not $.plugin().

You'd have to make plugin an object with a method property:

(function($) {

    // variables
    var test = [];

    $.plugin = {
        method: function(params){
            test.push(params['test']);
            console.log(test)
        }
    }

}(jQuery));

The immediate function ensures that test is only visible to $.plugin itself. You cannot access it from the outside. If you want to do that, you have to make it a property of $.plugin:

$.plugin = {
    test: [],
    method: function(params){
        this.test.push(params['test']);
        console.log(test)
    }
}

I suggest you first read a JavaScript guide [MDN guide] to learn the basics about functions [MDN guide] and objects [MDN guide].


What is $.plugin? I have no idea what you want, so here goes nothing:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$.plugin = {
    // Variable
    test: [],

    // Function
    method: function(params) {
        this.test.push(params['test']);
    }
};

$.plugin.method({
    test: 'helloworld'
});

$.plugin.method({
    test: 'another helloworld'
});

alert($.plugin.test);
</script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜