I'm creating an Javascript "class" with prototyping. I don't understand why the first/second block won't work, and the third block will work. For the first/second block I get: "Object # has no method 'validate' ". Why does it do that, and is block 3 the correct way?
--Edit I have tested this in Chrome/FF
--Edit2 If I call the Test prototype with: var test = new Test();
And call the test var in de login prototype it will work....
Block 1
function Test(){
this.init();
}
Test.prototype.init = function(){
$(".login").click(this.login);
};
Test.prototype.login = function(event){
event.preventDefault();
this.validate();
console.log("login");
};
Test.prototype.validate = function(){
console.log("validate");
};
new Test();
Block 2
function Test(){
this.init();
}
Test.prototype.init = function(){
$(".login").click(this.login);
};
Test.prototype.login = function(event){
var self = this;
event.preventDefault();
self.validate();
console.log("login");
};
Test.prototype.validate = function(){
console.log("validate");
};
new Test();
Block 3
function Test(){
if(!(this instanceof LoginController)){
return new LoginController();
}
self = this;
this.init();
}
Test.prototype.init = function(){
$(".login").click(this.login);
};
Test.prototype.login = function(event){
event.preventDefault();
self.validate();
console.log("login");
};
Test.prototype.validate = function(){
console.log("validate");
};
new Test();
self, which is never a good idea. I'd say that block 1 is the correct way to go. - Matteo Tassinari