I have read a few questions like this about it, but I still can't make it work:
Here is my simplified test:
var person = function(name, job)
{
var self = this;
self.name = null;
self.callMe = function()
{
alert(self.name + ' please!');
};
self.init = function()
{
self.name = name;
setTimeout(function(){self.callMe()}, 1000);
}();
}
...
person.prototype.callMe = function()
{
alert('Mister ' + this.name + ' please!');
};
var jonh = new person('john');
var joe = new person('joe');
can test it here: http://codepen.io/anon/pen/bqxmPa?editors=0010
1. Why is the callMe()
function in use the original one?
I have read that I must use this
to be able to use prototype, which makes sens: since I call a function stored in var self
from self.init()
the function stored in that var will not be modified by my later prototype... But then how do I do the callback if I don't store the this
in self
?
2. If I override callMe
like person.callMe = function(){};
it will do the same, then why should I use prototype?
I also understand that placing a method in a prototype is good for performance as it is not duplicated in each instance but still shared among them.
Thanks for your teaching!