Reputation: 214
so basically what i would like to ask you, when I use event listeners with function that has parameters why i can't use word this in function, this is an example for you, because i cant explain it properly.
var elUsername = document.getElementById('username');
var elMsg = document.getElementById('feedback');
function checkUsername(minLength){
if (elUsername.value.length < minLength){
elMsg.textContent = 'ur username must contain at least 5 chars';
}else {
elMsg = "";
}
}
elUsername.addEventListener('blur', function(){checkUsername(5)}, false);
------------------------------------------------------------
function checkUsername(){
var elMsg = document.getElementById('feedback');
if (this.value.length <5){
elMsg.textContent = 'usename must be 5 chars or more';
}else {
elMsg.textContent='';
}
}
var elUsername = document.getElementById('username');
elUsername.onblur = checkUsername;
so second example in function there is no parameter in if statement I can use this, but in first example i couldn't can some1 explain why is that?
Upvotes: 0
Views: 63
Reputation: 5353
A simplified explanation : they keyword this is available to any function that is owned by an object.
By doing :
elUsername.onblur = checkUsername;
You have attached your function to the object elUsername
. So this
will refer to the object elUsername but ONLY if the function is called using the onblur field : elUsername.onblur()
.
If you want to do the same on the first case, you can use the function call
to force the value of the parameter this
:
elUsername.addEventListener('blur', function(){
checkUsername.call(elUsername, 5)
}, false);
See https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Function/call
Upvotes: 0
Reputation: 2780
That is because you are calling the checkUsername
method from inside a anonymous function in your event listener, if you change
elUsername.addEventListener('blur', function(){checkUsername(5)}, false);
to
elUsername.addEventListener('blur', checkUsername, false);
and do the value check inside the function (like the second code example) it will work.
This happens because the scope of 'this' is not passed when you call checkUsername, this is possible, but that you'll have to call it with the .call()
method. Like so:
elUsername.addEventListener('blur', function(){checkUsername.call(elUsername, 5)}, false);
Now the elUsername
is passed as this
to the checkUsername
function.
Although i would prefer to directly call the checkUsername
function and do your calculations from there.
Upvotes: 1