有没有办法在原型中将函数参数用作 getter ?

Is there a way to use a function parameter as a getter in a prototype?

我正在尝试编写 pacman 代码,遇到了一个问题: 因为所有的幽灵都使用相同的寻路并且通常非常相似,所以我想为它们使用一个原型。他们唯一真正不同的 属性 是他们选择目标位置的方式。我想为原型提供一个函数并将其用作 getter。这可能吗?

function Ghost(color,x,y,getterFunction){
    this.color = color;
    this.x = x;
    this.y = y;
    this.direction = "up";
    this.move = function(){
        //Pathfind towards this.target
    }
    this.target = getterFunction; //or something like this...
}

感谢您的帮助:^)

@Bergi 是对的。您不想将其用作 getter。如果你试图将它添加到原型中,它会被你创建的每个新幽灵覆盖,因为原型是一个共享对象。

原型用于共享功能。实例功能属于实例,即在您的构造函数中。

你的移动函数应该在原型上。但是 target 应该是一个实例方法。您可以为原型上的目标设置默认方法。在查找原型之前将调用任何实例方法。

例子

function Ghost(color, x, y, target){
    // everything in here is instance specific
    this.color = color;
    this.x = x;
    this.y = y;
    this.direction = "up";

    if (typeof target === 'function') {
      this.target = target;
    }
}

// this is the prototype
Ghost.prototype.move = function() {
    //Pathfind towards this.target
    this.target()
}

Ghost.prototype.target = function() {
  // default target to use if no target provided at creation
}

现在,当你这样做时:

var redGhost = new Ghost('red', 0, 0, function() {
  //do something unique
})

你会得到一个红色的幽灵,它有一个自定义的目标函数。但是如果你这样做:

var yellowGhost = new Ghost('yellow', 0, 0)

您将拥有一个使用您添加到原型中的默认目标函数的幽灵。