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

时间:2017-01-30 15:20:43

标签: javascript parameters parameter-passing prototype getter

我现在正试图编码pacman,并遇到了一个问题: 由于所有Ghost都使用相同的路径查找并且通常非常类似,所以我想为它们使用原型。他们真正区别的唯一属性是他们选择目标位置的方式。我想为原型提供一个函数并将其用作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...
}

感谢您的帮助:^)

1 个答案:

答案 0 :(得分:3)

@Bergi是对的。您不希望将其用作吸气剂。如果您尝试将其添加到原型中,那么您创建的每个新鬼都会覆盖它,因为原型是共享对象。

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

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

实施例

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)

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

相关问题