Domanda

The following code works properly in Firefox but not in Chrome? If you comment out line 15 to prevent the error on line 7 (cannot find this.update()), the code continues to execute properly. I cannot see why the first set of definitions is different to the first.

if (typeof RegionUpdater == "undefined") {
    function RegionUpdater(param1, param2, param3) {
        this.paramA = param1;
        this.paramB = param2;
        this.paramC = param3;

        this.update();
    }

    RegionUpdater.prototype.update = function() {
        alert("hi there");
    };
}

var ru = new RegionUpdater("1", 2, "3");

function LolUpdater(param1, param2, param3) {
    this.paramA = param1;
    this.paramB = param2;
    this.paramC = param3;

    this.update();
}

LolUpdater.prototype.update = function() {
    alert("hi there");
};

var lu = new LolUpdater(1, 2, 3);

I've got a jsfiddle setup here: http://jsfiddle.net/XhbZ8/2/

EDIT: The only idea I've been able to come up with is that Chrome has some sort of speculative execution going on, but the fact that I also get the same problem in IE8 makes me less inclined to believe that's the case.

È stato utile?

Soluzione

First check Why are function declarations handled differently in different browsers?

This seems like a hoisting issue. The if statement gets ignored because this is what happens:

if (typeof RegionUpdater === 'undefined') {
  function RegionUpdater() {}
}

The above will be interpreted in the following because functions get hoisted (moved to) the top of the closest scope (function), in this case the scope is the global object.

function RegionUpdater() {}
if (typeof RegionUpdater === 'undefined') {
  // won't run since RegionUpdater is already defined
}

You could workaround it like this:

var RegionUpdater = RegionUpdater || function RegionUpdater(){

};

Edit: Like Mics said, using a function expression should work:

if (typeof RegionUpdater === 'undefined') {
  var RegionUpdater = function RegionUpdater(){};
  ...
}

Because this is how it happens:

var RegionUpdater;
if (typeof RegionUpdater === 'undefined') {
  RegionUpdater = function RegionUpdater(){};
  ...
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top