【问题标题】:Is there a way to use a function parameter as a getter in a prototype?有没有办法在原型中使用函数参数作为 getter?
【发布时间】:2017-01-30 15:20:42
【问题描述】:

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

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

感谢您的帮助:^)

【问题讨论】:

  • 没有。如果这就是它们的不同之处,那就是你不想想放在原型上的东西。
  • 只需使用this.target() 而不是this.target,您的代码应该可以工作。
  • 你考虑过使用 ES6 类吗?您可以使用 Babel 转译代码以在所有浏览器中工作
  • @royalsampler 无论如何我都不知道如何使用类...但是感谢 Babel 提示...我不知道。
  • @Bergi 我想简单地将其从原型中删除,但这使得一次性初始化对象成为不可能。之后我需要添加函数......但是根本不使用吸气剂的技巧很棒:) Tahnks!

标签: javascript parameters parameter-passing prototype getter


【解决方案1】:

@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)

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

【讨论】:

  • 这是一个很好的答案,但确实可以从一些示例代码中受益。
  • 现在这个答案真棒。 A+++ 会再次投票。
  • 谢谢 :) 你的帮助真的有帮助!
  • 我有一个问题:在原型中专门添加移动功能是否有区别,或者我可以将它留在原处吗?
  • 如果你把它留在构造函数中,每个实例都会得到该函数的一个新副本。如果您希望通过原型共享它,则必须将其添加到原型中。原型是一个单独的对象。每个实例都会获得对原型的引用,因此如果您尝试在您的实例上查找不存在的属性(例如移动),它会查找原型链以查看是否可以找到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-07
相关资源
最近更新 更多