Reputation: 592
I am trying to refactor this small chunk of code to define commonly-required variables and use them in the methods. Why does this.title work but this.dialogoverlay does not? The commented line works, but I want to refactor as stated so I don't have to use document.getElementById
over and over.
function CustomAlert(){
this.title = "This is My Title";
this.dialogoverlay = document.getElementById('dialogoverlay');
this.render = function(dialog){
// document.getElementById('dialogoverlay').style.display = "block";
this.dialogoverlay.style.display = "block";
document.getElementById('dialog-shadow').style.display = "block";
document.getElementById('dialogbox').style.display = "block";
document.getElementById('dialogboxhead').innerHTML = this.title;
document.getElementById('dialogboxbody').innerHTML = dialog;
etc...
I get "Can't set style of null."
Upvotes: 1
Views: 221
Reputation: 182
To answer your question, "Why does this.title work but this.dialogoverlay does not?".
What "this" refers to depends on how you are invoking the function. I would like to quote something from http://www.javascripttutorial.net/javascript-this/,
"A common mistake you may have is to think that this is the same in an inner function as in the outer function. The truth is that the context of the inner function depends on how it is invoked not the context of the outer function."
Upvotes: 2
Reputation: 451
Because this
in function reference to other variable. Try use dialog
instead this
Upvotes: 1