Can you explain me why does the second call of fn gives an error? The code is below.
function Test(n) {
this.test = n;
var bob = function (n) {
this.test = n;
};
this.fn = function (n) {
bob(n);
console.log(this.test);
};
}
var test = new Test(5);
test.fn(1); // returns 5
test.fn(2); // returns TypeError: 'undefined' is not a function
Here’s a JSfiddle that reproduces the error http://jsfiddle.net/KjkQ2/
Your
bobfunction is called from the global scope. Thefore,this.testis pointing at a global variable namedtestwhich is overwriting the variable you created. If you runconsole.log(window.test), you’ll what’s happening.For your code to behave as intended, you would need one of the following
OR
OR closure based objects