将我的 var 设置为带有参数的匿名函数?
我正在构建我的第一个 OO JS 库,但我在一个可能非常简单的部分上遇到了一点麻烦...
我有这个:
var storageLocker = function(catalog){
if(catalog){
this.catalog = catalog;
}
//my code...
}()
我需要能够做其他库(如 jQuery)所做的事情,您可以在其中选择一个元素(在我的案例选择一个 localStorage 项目),然后将其他功能链接到它。我已经完成了所有这些工作,但为了最佳实践并使其更具可扩展性,我将其放入匿名函数中,现在我无法弄清楚如何使用以下语法:
storageLocker('localStorageItem').save({"item":"an example item saved to localStorageItem"})
但现在如果我现在使用该语法执行此操作它返回此错误:
Uncaught TypeError: Property 'storageLocker' of object [object DOMWindow] is not a function
有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
删除函数体末尾的
()
。您编写了
var storageLocker = function(...) { ... }()
,它创建了一个匿名函数,调用它,并分配结果< /em> 到storageLocker
。它相当于
由于该函数不返回任何内容,
storageLocker
最终成为未定义
,并且不是一个函数。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 tostorageLocker
.It's equivalent to
Since the function doesn't return anything,
storageLocker
ends up beingundefined
, and is not a function.