Search code examples
javascriptobjectundefinedjavascript-objects

How to use object properties inside a parameterized function?


I have been working on a dialog in a project and I made it into an object constructor.

function createDialog(title, noClicked = function(){}, yesClicked = function(){}) {
  this.dialog = document.getElementsByClassName("dialog")[0];
  this.dialogTitle = this.dialog.getElementsByTagName("h1")[0];
  this.No = this.dialog.getElementsByTagName("button")[0];
  this.Yes = this.dialog.getElementsByTagName("button")[1];

  var dialog = document.getElementsByClassName("dialog")[0];
  this.dialogTitle.innerHTML = title;
  document.getElementsByClassName("dialogCon")[0].style.display = "flex";

  noClicked();

  yesClicked();
}
<div class="dialogCon">
      <div class="dialog">
        <h1></h1>
        <button type="button">No</button>
        <button type="button">Yes</button>
      </div>
    </div>

The problem is that when I want to access "this.no" or "this.yes" I keep getting Cannot read property 'No' of undefined. This happened when I used the below code:

var d = new createDialog("Sample dialog. Exit?", function() {
  console.log(d.No);
}, function() {
  console.log(d.Yes);
});

I need to use d.No to close the dialog. Is there any other way to do it? Or a fix at least.
I am aware of the fact that I could close the dialog from within the constructor itself, but I want to make it possible to do other stuff as well (like detecting whether user choose yes or no).

Thanks in advance

Solution

  • You are calling noClicked() and yesClicked() immediately inside constructor. I think you would want to call them on click of No and Yes. You need to add these functions to event listeners of the buttons. Try below snippet.

    function createDialog(title, noClicked = function(){}, yesClicked = function(){}) {
      this.dialog = document.getElementsByClassName("dialog")[0];
      this.dialogTitle = this.dialog.getElementsByTagName("h1")[0];
      this.No = this.dialog.getElementsByTagName("button")[0];
      this.Yes = this.dialog.getElementsByTagName("button")[1];
    
      var dialog = document.getElementsByClassName("dialog")[0];
      this.dialogTitle.innerHTML = title;
      document.getElementsByClassName("dialogCon")[0].style.display = "flex";
      this.No.addEventListener('click',noClicked);
      this.Yes.addEventListener('click',yesClicked);
    }
      
    
     var d = new createDialog("Sample dialog. Exit?", function() {
                   console.log(d.No);
                }, function() {
                   console.log(d.Yes);
               });
    <div class="dialogCon">
          <div class="dialog">
            <h1></h1>
            <button type="button">No</button>
            <button type="button">Yes</button>
          </div>
        </div>