myFunction.init() 是“不是函数” - 我怎样才能启动jquery代码?
我找不到启动脚本的正确方法。我有几个变量,所以文档准备好时的函数,然后是变量 myFunction 和 loadIMG 等,在代码末尾,调用 myFunction.init(),但 Firebug 告诉我“myFunction.init( ) 不是一个函数”。我怎样才能以正确的方式开始它? 感谢您的帮助:
$(function () {
//...
var myFunction = (function() {
var init = function() {
loadIMG();
},
loadIMG = function() {
etc.
//...
//then at the end of the page :
})(); /* myFunction */
myFunction.init();
});
i cannot find the right way to start the script. I have several variables, so the function when the document is ready, then the variable myFunction, and loadIMG, etc. and at the end of the code, the call to myFunction.init(), but Firebug tells me "myFunction.init() is not a function" . How could i start it the right way?
Thanks for any help :
$(function () {
//...
var myFunction = (function() {
var init = function() {
loadIMG();
},
loadIMG = function() {
etc.
//...
//then at the end of the page :
})(); /* myFunction */
myFunction.init();
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想将 myFunction 视为构造函数,您需要执行以下两件事之一。
使用您想要的方法返回一个对象。
实际上创建一个构造函数并使用
new
关键字。将任何公共方法/变量分配为this
的属性。If you want to treat
myFunction
as a constructor, you need to do one of two things.Return an object with the methods you want.
Actually make a constructor and use the
new
keyword. Allocate any public methods/variables as properties onthis
.您正在评估匿名函数,因为您正在编写
(function () {})()
而不仅仅是function () {}
,这是一个错误吗?如果不是,匿名函数是否返回一个新函数?检查typeof myFunction
以查看它是否确实是“function”
You are evaluating the anonymous function since you are writing
(function () {})()
instead of justfunction () {}
, is that a mistake? If not, does the anonymous function return a new function?. Checktypeof myFunction
to see if it is indeed"function"
您试图在函数可见的范围之外访问您的函数。由于您已在 $(function(){}) 内部声明了 myFunction 变量,因此它仅在该范围内可见。
如果您想在尝试访问的位置访问它,则需要在函数外部声明 myFunction,如下所示:
然后您可以在脚本中的任何位置引用 myFunction。
You're trying to access your function outside of the scope it's visible in. Since you've declared the myFunction variable INSIDE the $(function(){}) it is only visible in that scope.
If you want to access it at the point where you are trying to, you'll need to declare myFunction outside of the function as such:
Then you can refer to myFunction anywhere in the script.