当我把js逻辑写在闭包中作为一个单独的js文件时,一切都很好,如下:

(function(win){
   //main logic here
   win.expose1 = ....
   win.expose2 = ....
})(window)

但是当我尝试在同一个js文件中的闭包之前插入一个日志替代函数时,

 window.Glog = function(msg){
     console.log(msg)
 }
 // this was added before the main closure.

 (function(win){
   //the former closure that contains the main javascript logic;
 })(window)

它抱怨有一个TypeError:

Uncaught TypeError: (intermediate value)(...) is not a function

我做错了什么?


当前回答

当我创建一个新的ES2015类,其中属性名等于方法名时,我就遇到过这个问题。

例如:

class Test{
  constructor () {
    this.test = 'test'
  }

  test (test) {
    this.test = test
  }
}

let t = new Test()
t.test('new Test')

请注意这个实现在NodeJS 6.10中。

作为一种变通方法(如果你不想使用无聊的“setTest”方法名),你可以为你的“私有”属性使用一个前缀(如_test)。

在jsfiddle中打开开发人员工具。

其他回答

  **Error Case:**

var handler = function(parameters) {
  console.log(parameters);
}

(function() {     //IIFE
 // some code
})();

输出:TypeError:(中间值)(中间值)不是函数 *如何修复IT ->,因为你缺少半冒号(;)分开的表达式;

 **Fixed**


var handler = function(parameters) {
  console.log(parameters);
}; // <--- Add this semicolon(if you miss that semi colan .. 
   //error will occurs )

(function() {     //IIFE
 // some code
})();

为什么会出现这个错误? 原因: ES6标准中给出的自动分号插入的特定规则

当我创建一个新的ES2015类,其中属性名等于方法名时,我就遇到过这个问题。

例如:

class Test{
  constructor () {
    this.test = 'test'
  }

  test (test) {
    this.test = test
  }
}

let t = new Test()
t.test('new Test')

请注意这个实现在NodeJS 6.10中。

作为一种变通方法(如果你不想使用无聊的“setTest”方法名),你可以为你的“私有”属性使用一个前缀(如_test)。

在jsfiddle中打开开发人员工具。

如果来自Ionic Angular,则更新到最新版本

ng update @ionic/angular

当我创建根类时,我使用箭头函数定义了根类的方法。当继承和覆盖原来的函数时,我注意到同样的问题。

class C {
  x = () => 1; 
 };
 
class CC extends C {
  x = (foo) =>  super.x() + foo;
};

let add = new CC;
console.log(add.x(4));

这个问题可以通过定义父类的方法而不使用箭头函数来解决

class C {
  x() { 
    return 1; 
  }; 
 };
 
class CC extends C {
  x = foo =>  super.x() + foo;
};

let add = new CC;
console.log(add.x(4));

对我来说,这要简单得多,但我花了一段时间才弄明白。在。jslib中

some_array.forEach(item => {
    do_stuff(item);
});

结果Unity (emscripten?)就是不喜欢这种语法。我们用一个很好的for循环替换了它,它立即停止抱怨。 我真的很讨厌它不显示它所抱怨的行,但无论如何,愚弄我两次是我的耻辱。