javascriptjqueryhtmlcsshud

Can I add/declare properties to a function in JavaScript?


I'm developing a RPG using HTML, CSS and JavaScript with jQuery as a personal project. Right now I'm doing the HUD where the player will have buttons to display information such as the Character Information, inventory, etc. Each of these buttons on will create a div where the info required will be displayed, if clicked again and the div is open it will delete it (or close it).

As far as I understand, functions in JS are treated as objects and thus properties can be added, I want to add a boolean property to the function that creates the div as a flag to check if the window is open or closed so I don't have to declare a global variable as flag to each button.

How do I declare those properties in a function?

Example:

let windowCharInfo = () => {
  this.opened = false;
  this.windowDisplay = function() {
    $('<div>', {
        class: 'HUDWindow',
        id: 'charInfoWindow'
    }).appendTo('#charInfo'); // Here's the window that will be created

    // Some other code to add elements to that window will be here
  }
}

The let windowCharInfo() is already an object or do I have to store it in a variable using 'new' keyword?

Also, windowCharInfo() will be called when the user clicks '#charInfo' (using onclick: 'windowCharInfo()')


Solution

  • Here is a Simple Constructor:

    function Player(type) {
      this.type = type;
      this.weapons = []; // public
      var thaco; // private
      this.setTHACO = function(thaco) {
        this.thaco = thaco;
        return this;
      }
      this.getTHACO = function() {
        return this.thaco;
      }
      this.addWeapon = function(weapon) {
        this.weapons.push(weapon);
        return this;
      }
    }
    var player1 = new Player('elf'); // now it's an Object
    player1.addWeapon('sword').addWeapon('axe').setTHACO('18');
    console.log(player1.type);
    var weapons1 = player1.weapons;
    for (var i = 0, l = weapons1.length; i < l; i++) {
      console.log(weapons1[i]);
    }
    console.log(player1.getTHACO());