[英]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... 我正在建立我的第一个OO JS库,我在一件可能非常简单的作品上遇到了一些麻烦...
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. 我需要能够做其他类似jQuery的库那样的工作,在这里您可以选择一个元素(在我的情况下选择一个localStorage项),然后将其他函数链接到该元素。 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
. 您编写了
var storageLocker = function(...) { ... }()
,它创建了一个匿名函数, 将其调用 ,并将结果分配给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. 由于该函数不返回任何内容,因此
storageLocker
最终是undefined
,而不是一个函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.