javascript - Functions are not being assigned to another function's prototype in Chrome -


the following code works in firefox not in chrome? if comment out line 15 prevent error on line 7 (cannot find this.update()), code continues execute properly. cannot see why first set of definitions different 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 jsfiddle setup here: http://jsfiddle.net/xhbz8/2/

edit: idea i've been able come chrome has sort of speculative execution going on, fact same problem in ie8 makes me less inclined believe that's case.

first check why function declarations handled differently in different browsers?

this seems hoisting issue. if statement gets ignored because happens:

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

the above interpreted in following because functions hoisted (moved to) top of closest scope (function), in case scope global object.

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

you workaround this:

var regionupdater = regionupdater || function regionupdater(){  }; 

edit: mics said, using function expression should work:

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

because how happens:

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

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -