2011-08-02 6 views
1

これまでの私のコードにはPythonのこのビットを変換する方法:私はGlicko rating systemのJS/HTMLの実装に取り​​組んでいると重くpyglickoから借りてい慣用Javascriptを

// The q constant of the Glicko system. 
var q = Math.log(10)/400; 

function Player(rating, rd) { 
    this.rating = rating || 1500; 
    this.rd = rd || 200; 
} 

Player.prototype.preRatingRD = function(this, t, c) { 
    // Set default values of t and c 
    this.t = t || 1; 
    this.c = c || 63.2; 
    // Calculate the new rating deviation 
    this.rd = Math.sqrt(Math.pow(this.rd, 2) + (Math.pow(c, 2) * t)); 
    // Ensure RD doesn't rise above that of an unrated player 
    this.rd = Math.min(this.rd, 350); 
    // Ensure RD doesn't drop too low so that rating can still change 
    // appreciably 
    this.rd = Math.max(this.rd, 30); 
}; 
Player.prototype.g = function(this, rd) { 
    return 1/Math.sqrt(1 + 3 * Math.pow(q, 2) * Math.pow(rd, 2)/Math.pow(Math.PI, 2)); 
}; 
Player.prototype.e = function(this, p2rating, p2rd) { 
    return 1/(1 + Math.pow(10, (-1 * this.g(p2rd) * (this.rating - p2rating)/400))); 
}; 

- と言うことです、それを完全にリッピング。

これはかなり短く(コメントなしで100 LoC未満)、私の翻訳は正直なところ、私はJavaScriptのスコープとthisが実際にどのように動作するのか分からないので、私の翻訳がうまくいくかどうか不安を感じています。あなたは上のリンクにあるものを見ることができます。

具体的には、私はこのビットのPythonコードをJavascriptでどのように表現するのだろうと思います。基本的に_d2は、Playerのクラス定義の内部にあります。

def _d2(self, rating_list, RD_list): 
    tempSum = 0 
    for i in range(len(rating_list)): 
     tempE = self._E(rating_list[i], RD_list[i]) 
     tempSum += math.pow(self._g(RD_list[1]), 2) * tempE * (1 - tempE) 
    return 1/(math.pow(self._q, 2) * tempSum) 

私はそうのように定義された関数egを持っている、とqが一定である:JavaScriptで

Player.prototype.e = function(this, ratingList, rdList) { 
    // Stuff goes here 
} 

答えて

3

あなたはO明示的に自己を渡す必要はありません(Pythonは "あります奇妙な "ここに、実際に)

Player.prototype.e = function(rating_list, RD_list){ 
    //replace "self" with "this" here: 
    var tempSum = 0; //if you don't use the "var", tempSum will be a global 
        // instead of a local 
    for(var i=0; i<rating_list.length; i++){ //plain old for loop - no foreach in JS 
     var tempE = this._E(...); //note that in JS, just like in Python, 
            //variables like this have function scope and 
            //can be accessed outside the loop as well 
     tempSum += Math.pow(...) //the Math namespace is always available 
            //Javascript doesn't have a native module system 
    } 
    return (...); 
} 

これはすべて正常に動作するはずです。 thisについて知っておく必要がある厄介なことは、それが非常に混乱しているということだけです。これは、関数の呼び出し方法によって決まることを意味します。

obj.e(); //if you do a method-like call, the this will be set to obj 

ただし、舞台裏で魔法の拘束はありません。以下はPythonで動作しますが、ではなく、JavaScriptで動作します:

f = obj.e 
f(); //looks like a normal function call. This doesn't point to obj 
関連する問題