Skip to content

Instantly share code, notes, and snippets.

@emadb
Created October 28, 2014 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emadb/1354b4fa365997746168 to your computer and use it in GitHub Desktop.
Save emadb/1354b4fa365997746168 to your computer and use it in GitHub Desktop.
Spot the bug! Why doesn't doSomething print "new function"
function MyObject(fun){
this.fun = fun;
}
MyObject.prototype.doSomething = function() {
this.fun();
};
var f = function (){console.log('Original function')};
var myObj = new MyObject(f)
f = function (){console.log('new function')}
myObj.doSomething();
@unlucio
Copy link

unlucio commented Oct 28, 2014

function MyObject(options){
  this.fun = options.fun;
}

MyObject.prototype.doSomething = function() {
  this.fun();
};

var functions ={fun: function (){console.log('Original function')}};

var myObj = new MyObject(functions)

functions.fun = function (){console.log('new function')}

myObj.doSomething();

@unlucio
Copy link

unlucio commented Oct 28, 2014

questo invece si comporta come ti aspetteresti:

function MyObject(functions){
  this.functions = functions;
}

MyObject.prototype.doSomething = function() {
  this.functions.fun();
};

var functions ={fun: function (){console.log('Original function')}};

var myObj = new MyObject(functions)

functions.fun = function (){console.log('new function')}

myObj.doSomething();

@unlucio
Copy link

unlucio commented Oct 28, 2014

anyway: it's not a bug :)
it's about closuring and javascript execution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment