自我调用函数javascript [英] Self invoking functions javascript

查看:72
本文介绍了自我调用函数javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在firefox和chrome中都写了一个自调用函数,它不会调用它。

I wrote a self invoking function in both firefox and chrome it it wouldn't invoke.

我写了一些东西到

(function () { alert("THE"); })();

自我调用函数在当前浏览器中不起作用吗?

do self invoking functions not work in current browsers?

谢谢

编辑:我确实包含了所有基本标签,所有其他代码都在页面上工作

edit: I did include all essential tags and all other code works on the page

推荐答案

自我调用函数实际上并不是javascript的一部分,它只是一个人们称之为特定代码模式的术语(如AJAX等);这些模式应该适用于javascript工作的任何地方。

"Self-invoking functions" are not really a part of javascript, it's just a term that people are calling a specific pattern of code (like AJAX, etc.); these patterns should work anywhere that javascript works.

你所谓的自调用函数只是创建一个匿名函数并立即调用它(而不是比如将它存储在var中,作为对象值,作为函数参数等。)

What you're calling a "self-invoking function" is just creating an anonymous function and immediately calling it (as opposed to say storing it in a var, as an object value, as a function param, etc.).

即,以下内容基本相同:

That is, the following are basically the same:

var f = function(){...}; f()

( function(){...} )()

所以因为你的'自我调用函数'是javascript的基本部分,除非内部不起作用或你的环境搞砸了,否则它没有可行的方法。您可以将代码复制粘贴到新的空白页面上,它可以正常工作。其他一切都必须出错:

So because your 'self-invoking function' is a basic part of javascript, there is no possible way it's not working unless the insides aren't working or your environment is messed up. You could copy-paste your code onto a new blank page, and it would work fine. Something else must be going wrong:

在开发控制台中检查错误。具体来说,检查以确保您没有语法错误或者您正在测试它的网页上没有发生一些奇怪的事情(例如,如果您以某种方式重新定义 alert ...)。

Check your errors in your dev console. Specifically, check to make sure you don't have a syntax error or that there isn't some weird thing going on with the webpage you're testing it on (e.g. if you somehow redefine alert...).

这篇关于自我调用函数javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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