将我的var设置为带有参数的匿名函数? [英] Set my var to an anonymous function with a parameter?

查看:119
本文介绍了将我的var设置为带有参数的匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立我的第一个OO JS库,而我在一件可能超级简单的作品上遇到了一些麻烦...

I'm building my first OO JS library and im having a little trouble with one piece that's probably super easy...

我有这个:

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

我需要能够做其他与jQuery之类的库一样的工作,您可以在其中选择一个元素(在我的情况下,选择一个localStorage项),然后将其他函数链接到该元素.我已经做了所有的工作,但是为了最佳实践并为了使其更可扩展,后来我将其放在一个匿名函数中,现在我不知道如何使用以下语法:

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

有什么想法吗?

推荐答案

删除函数正文末尾的().

您编写了var storageLocker = function(...) { ... }(),它创建了一个匿名函数,调用了该函数,并将结果分配给了storageLocker.

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

等效于

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

由于该函数不返回任何内容,因此storageLocker最终成为undefined,而不是一个函数.

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

这篇关于将我的var设置为带有参数的匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆