如何通过构造函数中的点表示法调用私有方法?

时间:2017-06-14 17:51:54

标签: javascript oop

这是简历:如何通过构造函数中的点表示法调用私有方法?:

我知道有很多问题要问同样的......在这个特别的地方,我找不到任何地方,所以我决定问。

receiveAttackFrom()方法如何可以是私有的? 所以,如果我试试这个......

soldier1.receiveAttackFrom(soldier2, 50)

会抛出错误

var Soldier = function(_name, _life, _damage) {

var name = _name
var life = _life
var damage = _damage

this.getName = function() {return name}
this.getLife = function() {return life}
this.getDamage = function() {return damage}

this.setLife = function(_life) {life = _life}

this.attack = function(_targ) {

    _targ.receiveAttackFrom(this, this.getDamage());
}

// how to put this as a private method? :
this.receiveAttackFrom = function(_other, _damage) {

    this.setLife( this.getLife() - _damage )    
}

}

// MAIN
var soldier1 = new Soldier('jonas', 100, 25);
var soldier2 = new Soldier('mark', 90, 30);

soldier1.attack(soldier2);
// so if I try this...
// soldier1.receiveAttackFrom(soldier2, 50)
// would throw an error

2 个答案:

答案 0 :(得分:0)

var _self = this;
this.receiveAttackFrom = function(_other, _damage) {
    _self.setLife( _self.getLife() - _damage )    
}

答案 1 :(得分:0)

使用var在构造函数的开头定义函数并将其绑定到this

var receiveAttackFrom = function (_other, _damage) {
    this.setLife( this.getLife() - _damage )    
}.bind(this);

然后在没有前缀的构造函数内调用它:

receiveAttackFrom(arg1, arg2);