本文介绍了Javascript:将命名函数分配给变量(命名函数表达式)时不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释Internet Explorer和Firefox之间在以下方面的差异:

Can anyone explain the difference in behaviour between Internet Explorer and Firefox in regards to the below:

var myNamespace = (function () {
  var exposed = {};

  exposed.myFunction = function myFunction () {
    return "Works!";
  }

  console.log(myFunction()); 
  // IE: "Works!"
  // Firefox: ReferenceError: myFunction is not defined

  console.log(exposed.myFunction());
  // IE: "Works!"
  // FF: "Works!"

  return exposed;
})();

console.log(myNamespace.myFunction()); 
// IE: "Works!"
// FF: "Works!"

在Internet Explorer中,这个方法允许我从命名空间函数中调用我的函数,使用 myFunction() exposed.myFunction()

In internet explorer this method allows me to call my function from inside my namespace function by using either myFunction() or exposed.myFunction().

我的namepsace函数我可以使用 myNamespace.myFunction()

Outside my namepsace function I can use myNamespace.myFunction()

在Firefox中,

In Firefox, the results are the same with the exception of the bare named function call which does not work.

它应该工作吗?

如果它应该是一个已知的错误?

If it should then is this a known bug?

推荐答案

为了防止出现错误信息:

To prevent false information:

IE有命名函数表达式的问题, 。函数的名称只应在功能中可用。从:

IE has a problem with named function expressions which is what you have. The name of the function should only be available inside the function. From the specification:

其中FunctionExpression定义为:

where FunctionExpression is defined as:

但是在IE中,并不是只在函数内部使用该名称,而是创建两个不同的分配给变量,另一个赋给您给出的函数的名称。以下将在IE中产生 false (并在其他浏览器中抛出错误):

But in IE, instead of making the name only available inside the function, it creates two different function objects, one assigned to the variable and the other to the name you gave the function. The following will yield false in IE (and throw an error in other browsers):

exposed.myFunction === myFunction;

这是一个已知的错误,如果您必须为IE的旧版本编写代码,命名函数表达式。

It's a known bug and if you have to code for (older versions of) IE, you better avoid named function expressions.

相关问题:




  • detachEvent not working with named inline functions
  • Named Function Expressions in IE, part 2

这篇关于Javascript:将命名函数分配给变量(命名函数表达式)时不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 04:18