2017-06-14 62 views
0

這是簡歷:如何通過點符號調用一個私有方法內部構造?:如何通過構造函數中的點符號來調用私有方法?

我知道有很多問題問同一個...在這個格外我coulnd't找到任何地方,所以我決定問。

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 
+1

爲什麼你認爲它應該是私有的? –

+0

什麼是錯誤信息? – PeterMader

+0

這段代碼沒有錯誤......我只是想讓公共方法成爲一種私有方法。但在構造函數中使用點符號 –

回答

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

評論/解釋你的答案將有助於OP並提高其長期價值。 –

0

在你的構造與var開始定義功能,綁定到this

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

然後調用它的構造函數中不帶前綴:

receiveAttackFrom(arg1, arg2); 
相關問題