在对象中追加或编辑函数的最快方法是什么

Whats the quickest way to append or edit a function in an object?

本文关键字:方法 是什么 函数 编辑 对象 追加      更新时间:2023-09-26

我有一个这样的示例对象:

var shooter = {fire : function(){shootRightHandGun("shotgun");}}
但是,假设射手

找到了一把新枪,我们想将射手的射击功能设置为:

{fire : function(){shootRightHandGun("shotgun"); shootLeftHandGun("handgun");}}

实现这一目标的最佳/最快方法是什么?帮助程序函数,对象中的函数数组,任何东西。我完全愿意接受建议。

您不应该为此替换函数,而是单独跟踪项目,从长远来看,这可能会对您有所帮助。
您可能需要在代码的不同位置引用射手持有的当前项目,进行各种检查和验证。
不要只是替换这样的函数。

var shooter = {
    leftGun: null,
    rightGun: "shotgun",
    fire: function() {
        if(this.rightGun != null) {
            shootRightHandGun(this.rightGun);
        }
        if(this.leftGun != null) {
            shootLeftHandGun(this.leftGun);
        }
    }
}
shooter.leftGun = "handgun";

稍后,您可以使用适当的 setter 和 getter 轻松扩展代码,轻松添加一些额外的检查,因此:

getRightGun: function() { return this.rightGun; }
setRightGun: function(newRightGun) {
    if(isProperGun(newRightGun)) {              // some kind of a check
        this.rightGun = newRightGun;
    }
}

从技术上讲,您可以通过 .toString() 方法获取函数的源代码来编辑函数,然后使用 regexp 等对其进行字符串操作。但它会非常非常混乱,我不推荐它。

相反,为对象提供更多的结构。首先区分左右武器:

var shooter = {
    rightHand : function () {},
    leftHand : function () {},
    fire : function () {}
}

现在让.fire()方法射击(或使用)所有武器:

var shooter = {
    rightHandWeapon : function () {},
    leftHandWeapon : function () {},
    fire : function () {
        this.rightHandWeapon();
        this.leftHandWeapon();
    }
}

现在,上面的代码什么都不做(因为两个函数都不做),这意味着上面的代码适用于手无寸铁的射手。

现在您可以将武器实现为函数:

function shotgun () {
    /* code to fire shotgun */
}
function handgun () {
    /* code to fire handgun */
}

为了完整起见,我们还可以定义以下函数:

function unarmed () {};

现在你可以通过给射手武器来武装他:

// Armed with shotgun
shooter.rightHandWeapon = shotgun;
shooter.fire();
// Armed with shotgun and handgun:
shooter.rightHandWeapon = shotgun;
shooter.leftHandWeapon = handgun;
shooter.fire();
// Armed with TWO shotguns:
shooter.rightHandWeapon = shotgun;
shooter.leftHandWeapon = shotgun;
shooter.fire();
// Disarm the shooter:
shooter.rightHandWeapon = unarmed;
shooter.leftHandWeapon = unarmed;
shooter.fire(); // does nothing

要追加

var temp = shooter.fire;
shooter.fire = (function(t){
    return function(){
    t();
    shootLeftHandGun("handgun");
  }
})(temp);

要编辑

shooter.fire = function(){shootLeftHandGun("handgun");};

小提琴:https://jsfiddle.net/trex005/4rhq7zxj/

如果用户能找到更好的枪,一个好方法是对Gun类使用继承。

es6 中的示例,但您可以使用原型在 es5 中轻松执行此操作:

class SimpleGun {
    fire: function() {
       shootLeftHandGun("handgun");
    }
}

class BetterGun extends SimpleGun {
    fire: function() {
        super.fire();
        shootRightHandGun("handgun");
    }
}

所以,当用户找到另一把枪时,只需做这样的事情:

user.setGun(new BetterGun())

只要你的对象不是函数构造函数,只是像这样的简单对象,你可以直接添加任何你想要的东西(属性、方法):

shooter.shootLeftHandGun  = fucntion() {// Your code here. }

但是,如果您的射击游戏是从函数构造函数创建的(在您的情况下并非如此),则可以通过对象的原型轻松完成此操作。

shooter.prototype.shootLeftHandGun = function() {// Your code here.}

与其简单地动态创建对象,不如尝试使用这个:]

function shooter() {
   this.shootRightHandGun = function() {
       // Code
   }
   this.name = "default name"
}
var newShooter = new shooter();
newShooter.prototype.shootLeftHandGun = function() { // Your new stuff.}

这是另一种选择:

var shooter = {
    guns:[{side:'right',type:'shootgun'}],
    fire : function(){
        for(var i = 0; i < this.guns.length; i++){
          this.shoot(this.guns[i]);
        }
    },
    gainGun : function(side, type){
        this.guns.push({side:side, type:type})
    },
    shoot:function(gun){
        console.log(gun)
    }
  }

看起来每个人都在这里堆积,这很酷。这是我的尝试。如果一把枪已经装备在手里,那么这只手就会被占用,并告诉用户。为了好玩,我还添加了一个fireAllGuns函数。

var shooter = {
  guns: {},
  fire: function(hand) {
    if (this.guns[hand]) {
      console.log("Firing " + this.guns[hand] + " from " + hand + " hand!");
    } else {
      console.log("There is no gun in that hand!")
    }
  },
  fireAllGuns: function() {
    for (var key in this.guns) {
      if (this.guns.hasOwnProperty(key)) {
        console.log("Firing " + this.guns[key] + " from " + key + " hand!");    
      }
    }
  },
  equipGun: function(hand, gun_name) {
    if (!this.guns[hand]) {
      this.guns[hand] = gun_name;
      console.log("Equipped " + gun_name + " in " + hand + " hand");
    } else {
      console.log("That hand is already occupied!")
    }
  }
};
shooter.fire("left");
// There is no gun in that hand!
shooter.equipGun("left", "pistol");
// Equipped pistol in left hand
shooter.fire("left");
// Firing pistol from left hand!
shooter.fire("right");
// There is no gun in that hand!
shooter.equipGun("right", "bazooka");
// Equipped bazooka in right hand 
shooter.fire("right");
// Firing bazooka from right hand!
shooter.fireAllGuns();
// Firing pistol from left hand!
// Firing bazooka from right hand!