【问题标题】:Declare method outside of class在类外声明方法
【发布时间】:2015-07-27 20:54:00
【问题描述】:

我知道我可以通过以下方式添加方法:

point.prototype.move = function () 
{
     this.x += 1;
}

但是,有没有办法通过将在其外部声明的函数分配给其属性之一来向类添加方法? 我很确定这行不通,但它让我知道我正在尝试做什么:

function point(x, y)
{
     this.x = x;
     this.y = y;
     this.move = move();
}

function move()
{
     this.x += 1;
}

【问题讨论】:

  • 嗯,你测试了吗?

标签: javascript methods


【解决方案1】:

您的示例不起作用的唯一原因是您正在调用move() 并分配其未定义的结果。

您应该在分配时只使用对move 函数的引用。

function move()
{
     this.x += 1;
}

function point(x, y)
{
     this.x = x;
     this.y = y;
     this.move = move
}

不同的方法

// Attach the method to the prototype
// point.prototype.move = move;

// Attach the method to the instance itself
// var myPoint = new point(1,2); myPoint.move = move; 

【讨论】:

    【解决方案2】:
    function point(x, y, move)
    {
         this.x = x;
         this.y = y;
         this.move = move;
    }
    
    function move()
    {
         this.x += 1;
    }
    
    var obj =  new point(2, 5, move);
    

    【讨论】:

      猜你喜欢
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 2021-07-08
      相关资源
      最近更新 更多