Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

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

This comment has been minimized.

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

This comment has been minimized.

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
You can’t perform that action at this time.