gpt4 book ai didi

javascript - 有没有办法在原型(prototype)中使用函数参数作为 getter ?

转载 作者:行者123 更新时间:2023-11-28 18:09:27 24 4
gpt4 key购买 nike

我现在正在尝试编写 pacman 代码,遇到了一个问题:由于所有幽灵都使用相同的寻路并且通常非常相似,因此我想为它们使用原型(prototype)。他们唯一真正不同的属性是他们选择目标位置的方式。我想为原型(prototype)提供一个函数并将其用作 setter/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 是对的。你不想用它作为 setter/getter 。如果您尝试将其添加到原型(prototype)中,它将被您创建的每个新幽灵覆盖,因为原型(prototype)是一个共享对象。

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

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

示例

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)

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

关于javascript - 有没有办法在原型(prototype)中使用函数参数作为 getter ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41939406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com