我正试图制作一个基本上说这个的IF声明......
“如果''''是'播放器'的原型,那么...”,但我不太确定如何在代码中写这个。如果角色是IS,那么它将与玩家路线一起使用。如果不是,那么它会将其检测为怪物并改为运行相反的功能。
var actor = {
expCounter: function (character){
if (player){ // This is what I want to change
$("#playerexpbaroverlay").animate({
height: dwarf.exp
}, 200);
}
else if (monster){ //if character is not a prototype of player, do this
$("#bossexpbaroverlay").animate({
height: dwarf.exp
}, 200);
}
if (dwarf.exp > 199){
dwarf.level++
dwarf.exp = 1;
dom.setText("playerlevel", dwarf.level)
$("#playerexpbaroverlay").animate({
height: dwarf.exp
}, 100);
}
}
}
我有额外的代码:
New = Object.create;
player = New (actor),
monster = New (actor),
dwarf = New(player),
angel = New(monster);
答案 0 :(得分:1)
另一种方式,只需将 isPlayer 添加到播放器对象中,例如
var actor = {};
New = Object.create;
var player = New(actor),
monster = New(actor),
dwarf = New(player),
angel = New(monster);
player.isPlayer = true;
function Check(character) {
if (character.isPlayer) {
console.log('player');
} else {
console.log('not player');
}
}
Check(dwarf);
Check(angel);
答案 1 :(得分:0)
你试过 isPrototypeOf() 吗? isPrototypeOf()方法测试另一个对象的原型链中的对象。
答案 2 :(得分:0)
只需使用instanceof
这样的方法
if(player instanceof Player){ //player is your actual function / class you created instance from
}else if(monster instanceof Monster){
// do something
}
答案 3 :(得分:0)
你可以使用instanceof检查一个对象是否具有另一个原型链的原型。
Object.create()函数可用于继承另一个'类的原型:
var New = Object.create;
function Actor() {}
// Player > Actor
function Player() {}
Player.prototype = New(Actor.prototype);
// Monster > Actor
function Monster() {}
Monster.prototype = New(Actor.prototype);
// Dwarf > Player > Actor
function Dwarf() {}
Dwarf.prototype = New(Player.prototype);
// Angel > Monster > Actor
function Angel() {}
Angel.prototype = New(Monster.prototype);
// create the instance
var angel = new Angel();
console.log(angel instanceof Player); // false
console.log(angel instanceof Monster); // true
console.log(angel instanceof Actor); // true
答案 4 :(得分:0)
假设你有一个定义类型为玩家的对象的Javascript类,或者别的......你可以这样做:
function Monster(name) {
this.name = name;
}
function Player(name) {
this.name = name;
}
var hitmands = new Player('hitmands');
var sagat = new Monster('Sagat');
console.log('is hitmands a monster?', hitmands instanceof Monster);
console.log('is hitmands a Player?', hitmands instanceof Player);

这样做的一个好方法是为每个类分配一个静态方法,检查给定实例是否属于确定的原型链:
function Monster(name) {
this.name = name;
}
function Player(name) {
this.name = name;
}
Player.is = function(data) {
return data instanceof Player;
}
Monster.is = function(data) {
return data instanceof Monster;
}
var hitmands = new Player('hitmands');
var sagat = new Monster('Sagat');
console.log('is hitmands a monster?', Monster.is(hitmands) );
console.log('is hitmands a Player?', Player.is(hitmands) );

不幸的是,javascript没有提供任何方法来实现Operator overloading
进一步阅读: