在 javascript 中自动调用匿名函数时出错

Error while making autocalling anonymous function in javascript

我不知道为什么这在到达匿名函数时给我一个错误。我发现如果它位于 .js 文件的顶部,它就不会发生。我不明白为什么会发生这种情况,因为不需要从该函数内部读取可能尚未读取的任何内容...任何解决方案?

function animate_get(selector) {
  var obj = new anim_object(element);
  return obj;
}

function anim_object(element) {}
anim_object.prototype.animate = function(params) {}

(function() {
  alert("yes!");
})()

显示的错误是:Uncaught TypeError: (intermediate value)(...) is not a function(...)

奇怪的是它位于顶部时没有出现(复制粘贴,所以我认为它写得正确)。

function animate_get(selector) {
  var obj = new anim_object(element);
  return obj;
}

function anim_object(element) {}
anim_object.prototype.animate = function(params) {}; // <=== ; added

(function() {
  alert("yes!");
})()

这就是为什么 IFFE 经常这样写的原因

;(function() {
  alert("yes!");
})()

这也是为什么我认为 ;不像 javascript 语言的松散早期规范所允许的那样可选

我jshint/jslint我的代码,然后放置;他们建议的地方

那么,这样的事情就不会发生了

你的代码在 js 引擎中看起来像这样

anim_object.prototype.animate = function(params) {} (function() {alert("yes!");})()

或者,一般来说

a = function(p){}(function() {})()

如果 "right" 代码在 {} 的集合之间,这可能是有效的语法 - 例如

var a = function(p){return function(a) { return a+p(); }}(function() {return ' <== value is in the last ()';})()
                   ^------first set of {}---------------^            ^-----------second set of {}-----------^

哪里

function anim_object(element) {} anim_object.prototype.animate = function(params) ...

function a {} b = function(params) ...

无论{}的内容如何都无效