我可以在JavaScript中为函数添加/声明属性吗?

时间:2017-11-30 01:31:17

标签: javascript jquery html css hud

我正在使用HTML,CSS和JavaScript开发RPG,并将jQuery作为个人项目。现在我正在进行HUD,播放器将有按钮显示信息,如字符信息,库存等。每个按钮都会创建一个div,如果再次点击,将显示所需的信息。 div打开它将删除它(或关闭它)。

据我所知,JS中的函数被视为对象,因此可以添加属性,我想在函数中添加一个布尔属性,将div创建为一个标志,以检查窗口是打开还是关闭所以我不必将全局变量声明为每个按钮的标志。

如何在函数中声明这些属性?

示例:

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
  }
}

let windowCharInfo()已经是一个对象,或者我必须使用&#39; new&#39;将它存储在一个变量中。关键字?

此外,当用户点击&#39;#charInfo&#39;时,将调用 windowCharInfo()。 (使用 onclick:&#39; windowCharInfo()&#39;

1 个答案:

答案 0 :(得分:0)

这是一个简单的构造函数:

function Player(type){
  this.type = type; this.weapons = []; // public
  var thaco; // private
  this.setTHACO = function(thaco){
    thaco = thaco;
    return this;
  }
  this.getTHACO = function(){
    return 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(player.type);
var weapons1 = player1.weapons;
for(var i=0,l=weapons1.length; i<l; i++){
  console.log(weapons[i]);
}
console.log(player1.getTHACO());
相关问题