javascript - 在类外声明方法

标签 javascript methods

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

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

最佳答案

您的示例不起作用的唯一原因是因为您正在调用 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; 

关于javascript - 在类外声明方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31663106/

相关文章:

javascript - 使用 MongoDB,如何使用变量中的对象更新数组中的对象?

当调用外部方法时,嵌套在方法中的Python字典会自动执行所有值(方法)

actionscript-3 - ActionScript 3 覆盖方法 + 提高可见性

java - 变量未在函数中初始化

javascript - 将脚本添加到 HTML 中的 assetbundle

javascript - Jquery 单独的多选选项更新价格变化

javascript - 获取 JSON 数组中的键值

javascript - 使用 jQuery 以多按钮形式运行加载动画

Java:ArrayList(三个类)中两个方法的可访问性问题

java - 如何覆盖java类中的单个方法