开发者

Set my var to an anonymous function with a parameter?

I'm building my first OO JS library and 开发者_高级运维im having a little trouble with one piece that's probably super easy...

I have this:

var storageLocker = function(catalog){
    if(catalog){
        this.catalog = catalog;
    }
    //my code...
}()

i need to be able to do what other libraries like jQuery do where you can select an element (in my case select a localStorage item) and then chain other functions to it. I had all that working, but for best practice and to make it more extensible later i put it in a anonymous function and now i can't figure out how to have the syntax of:

storageLocker('localStorageItem').save({"item":"an example item saved to localStorageItem"})

but right now if i do that now with that syntax it returns this error:

Uncaught TypeError: Property 'storageLocker' of object [object DOMWindow] is not a function

Any ideas?


Remove the () at the end of the function body.

You wrote var storageLocker = function(...) { ... }(), which creates an anonymous function, calls it, and assigns the result to storageLocker.

It's equivalent to

function anonymous(...) { ... };
var storageLocker = anonymous();

Since the function doesn't return anything, storageLocker ends up being undefined, and is not a function.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜