【问题标题】:A closure name clashes with function of same name inside it, but only in Chrome闭包名称与其中的同名函数冲突,但仅限于 Chrome
【发布时间】:2012-11-27 17:19:52
【问题描述】:

这会被认为是 Chrome 错误还是 Safari/Firefox 的宽大处理?

当我创建一个闭包函数时,我给它一个任意的名字,“按钮”。在闭包中,我有一个函数,它是闭包创建的主要对象的构造函数,也称为“按钮”。

闭包返回一个对Button的引用,大概是内部函数Button()。

var closure = (function Button(){

    //the closure's primary object
    function Button(target) {
        //constructor for our button object
    }

    Button.prototype = e.inherit(e.Plugin.prototype);
    Button.prototype.constructor = Button;

    return {
            Button: Button,
        };

}());

//now let's call our closure to create a new Button
var newButton = new closure.Button()

在 Safari 和 Firefox 中,这不是问题。调用 newclosure.Button() 返回内部 Button() 的一个实例。然而,在 Chrome 中,当内部函数名称与闭包函数名称匹配时,构造函数似乎不会被调用。返回的似乎是闭包函数本身。当然,当内部函数定义我稍后尝试调用的方法时,这会导致错误。

我发布这个问题有两个原因:

1) 我花了一天多的时间才找到问题的原因,这是 Chrome 报告我的 Button 没有方法 .activate (在我的真实代码中,Button 继承自提供 .激活()方法)。如果其他人遇到这个问题,那么他们可能会在这里找到我的问题并节省一些时间。

2) 我想知道:如果这是我的错误,为闭包和闭包中的函数使用相同的名称,为什么它在 Safari/Firefox 中工作?更具体地说,Chrome 是否确实以某种方式使闭包返回本身而不是预期的内部功能?这是一个错误吗?

【问题讨论】:

  • Chrome 中没有复制:jsfiddle.net/77LZh
  • 我听说过 IE 中的命名函数表达式存在问题(请参阅 here),但 Chrome 中没有。事实上,@SeanKinsey 的测试似乎在 Chrome 中运行良好。是什么让你觉得构造函数没有被调用?

标签: javascript google-chrome closures


【解决方案1】:

可能不是确切的问题,但您不必要地命名了函数表达式。

var closure = (function Button(){

    //the closure's primary object
    function Button(target) {
        //constructor for our button object
    }

    Button.prototype = e.inherit(e.Plugin.prototype);
    Button.prototype.constructor = Button;

    return {
            Button: Button,
        };

}());
//now let's call our closure to create a new Button
var newButton = new closure.Button()

应该是

var closure = (function (){

    //the closure's primary object
    function Button(target) {
        //constructor for our button object
    }

    Button.prototype = e.inherit(e.Plugin.prototype);
    Button.prototype.constructor = Button;

    return {
            Button: Button
        };

}());

//now let's call our closure to create a new Button
var newButton = new closure.Button();

不同之处在于顶层函数是未命名的。无需命名您将永远不会再使用的东西。

此外,返回对象中不应包含逗号。这应该是一个语法错误。

另外,最后一行没有结束分号。

【讨论】:

  • 这无济于事——JavaScript 的词法作用域防止了这成为问题。关于 command 和 semi 的 nits 足够正确,但对这个问题并不谨慎。
  • @SeanKinsey 我不会说它没有帮助。尽管您是对的,但很难解决您无法重现的问题。我只是想尝试一下。
猜你喜欢
  • 1970-01-01
  • 2015-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-27
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
相关资源
最近更新 更多