【问题标题】:Is it possible ? "Javascript Subclass"是否可以 ? “Javascript 子类”
【发布时间】:2012-04-07 01:22:05
【问题描述】:

我想知道我可以在 javascript 中做一些与此(不工作)代码“相似”的事情吗?

function Player ()     {

    this.Inventory = function ()     {

        this.Inventory.UseItem = function(item_id)    {
            /* use the item ... */
        }

    }

}

然后像这样使用它:

current_player = new Player();
current_player.Inventory.UseItem(4);

【问题讨论】:

  • 值得注意的是,术语“子类”在标准用语中通常意味着其他东西——这里的“库存”实际上只是播放器字段中的一个对象。
  • 确实,这是组合而不是继承。

标签: javascript class object subclass


【解决方案1】:
function Player() {
    this.Inventory = {
        UseItem: function(item_id) {
            // code here
        }
    };
}

试试看。

【讨论】:

    【解决方案2】:
    current_player = new Player();
    current_player.prototype.Inventory = {
             UseItem : function(item_id)    {
                /* use the item ... */
            }
    }
    

    【讨论】:

      【解决方案3】:

      是的

      function Player ()     {
      
          var Inventory = {
      
      
              UseItem : function(item_id)    {
                  /* use the item ... */
              }
      
          };
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-10
        • 1970-01-01
        • 2015-03-21
        • 2012-03-27
        • 2019-08-28
        • 2017-11-02
        • 1970-01-01
        相关资源
        最近更新 更多