Consider following example:
var Foo=function () {
var number = 1;
self.number = 1;
}
Foo.prototype.bar = function () {
console.log("test");
};
var foo = new Foo();
foo.bar();
Notice here that in line Foo.prototype.bar = function () I didn't write "var".
This code will work perfectly, in console you will see "test".
Now check following code:
var Foo=function () {
var number = 1;
self.number = 1;
return {inc: function() {
self.number = self.number + 1;
}}
}
Foo.prototype.bar = function () {
console.log("test");
};
var foo = new Foo();
foo.bar();
This code will not work, we will receive error "Uncaught TypeError: undefined is not a function", because with return we will loose "this". Solution is to add return this:
var Foo=function () {
var number = 1;
self.number = 1;
return this;
}
Foo.prototype.bar = function () {
console.log("test");
};
var foo = new Foo();
foo.bar();