使用方法修改对象属性

Modifying object properties with a method

所以我正在尝试编写一个简单的游戏来处理对象并习惯于操纵和使用它们。我想要做的是设置基本统计信息(user/programmer 已定义),然后在方法中使用这些基本统计信息来创建复杂的统计信息。我正在尝试做的示例代码:

var main = function() {
   function Boss (name, lvl, str, dex, int) {
      this.bName = name
      this.level = lvl
      this.strength = str
      this.dexterity = dex
      this.intelligence = int
      this.pAttack  = pAttack();
    }
     function pAttack() {
       (2*this.level) + (2*this.strength);
     }
      var a1Boss = new Boss("test", 50, 500, 500, 500)
      console.log(a1Boss.pAttack)
    }  

此 returns 未定义到控制台,但其他一切 returns 正确。 pAttack 函数是否应该设置为 var pAttack = function() {code}

如有任何帮助,我们将不胜感激

目前 pAttack 未在 Boss 实例的上下文中调用,因此 this 未指向您期望的内容,您有 3 个选项

在所有情况下,不要忘记从 pAttack 函数中 return


选项 1,让实例继承 pAttack

定义pAttack后,添加如下

Boss.prototype.pAttackFn = pAttack;

这是做什么的?
它使 Boss 的所有实例,即由 new Boss 构造的 Objects,继承函数 pAttack 作为 属性 pAttackFn 所以你可以这样称呼它

this.pAttack = this.pAttackFn();

选项 2,使用 .call.apply

定义调用上下文
this.pAttack  = pAttack.call(this);

选项3,给pAttack参数而不是依赖this

function pAttack(lvl, str) {
    return (2 * lvl) + (2 * str);
}

然后

this.pAttack  = pAttack(this.level, this.strength);

您的函数需要 return 一个值。但是,我会将其创建为对象的方法,并这样称呼它:

var main = function() {
    function Boss(name, lvl, str, dex, int) {
        this.bName = name;
        this.level = lvl;
        this.strength = str;
        this.dexterity = dex;
        this.intelligence = int;
        this.pAttack = function() {
            return (2 * this.level) + (2 * this.strength);
        }
    }
    var a1Boss = new Boss("test", 50, 500, 500, 500);
    console.log(a1Boss.pAttack());
};

main(); // outputs '1100' to the console

大量语法错误。

function Boss (name, lvl, str, dex, int) {
    this.bName = name;
    this.level = lvl;
    this.strength = str;
    this.dexterity = dex;
    this.intelligence = int;
    this.pAttack  = this.pAttack();
}
Boss.prototype = {
    pAttack: function () {
        return (2*this.level) + (2*this.strength); 
    },
    pDefend: function () {
        //Defend stuff
    },
    levelUp: function () {
        this.level = this.level + 1;
    }
};

var a1Boss = new Boss("test", 50, 500, 500, 500);
console.log(a1Boss.pAttack)

https://jsfiddle.net/sLhrek8h/1/

如果您希望将您的方法附加到新对象,请执行以下操作:

this.pAttack = pAttack;
// and the function should be initialized as a variable
var pAttack = function(){...};

如果您希望将您的方法附加到原型:

Boss.prototype.pAttack = pAttack;

您实际上执行了方法 pAttack 而不是分配它。由于 pAttack return 什么都没有,undefined 被 return 编辑为替代。

所以不要执行它,

this.pAttack  = pAttack;

或return某事

function pAttack() {
    return (2*this.level) + (2*this.strength);
}

根据您在长期 运行 中所做的事情,另一种可能有所帮助的解决方案是将参数传递给您的函数,然后返回该值。

function pAttack(level, strength) {
   return (2*level) + (2*strength);
}

并用

调用它
this.pAttack = pAttack(this.level, this.strength);