访问原型中的主要对象变量

时间:2017-03-11 18:27:19

标签: javascript prototype

我有这个对象

rsa = {
    publicKey: function(bits, n, e,r) {
        this.bits = bits;
        this.n = n;
        this.e = e;
        this.r = r;
    },
    generateKeys: function(bitlength) {
        var p, q, n, phi, e, d, r, keys = {}; //array vacidos de keys
        // if p and q are bitlength/2 long, n is then bitlength long
        this.bitlength = bitlength || 2048; //coge 2048 si no esta paso el bit length y si esta pasado coge valor bitlength
        console.log("Generating RSA keys of", this.bitlength, "bits");
        p = bignum.prime(this.bitlength / 2);
        do {
            q = bignum.prime(this.bitlength / 2 + 1);
        } while (q.cmp(p) === 0); //0 si p y q son identicoss
        n = p.mul(q);

        phi = p.sub(1).mul(q.sub(1));

        e = bignum(65537);
        d = e.invertm(phi);
        //random to blind
        var r = (bignum(2).rand(n));  
        keys.publicKey = new rsa.publicKey(this.bitlength, n, e, r); //genera una nueva public key
        keys.privateKey = new rsa.privateKey(p, q, d, keys.publicKey);//genera una nueva private key
        return keys; //return public and private key
    } 
};

然后我有了Object的这些原型,如何从原型中访问Object中的变量..

rsa.publicKey.prototype = {
    encrypt: function(m) {
        return m.powm(this.e, this.n);
    },
    verify: function(c) {
        return c.powm(this.e, this.n);
    },
    //blind message
     blind: function(m){
         var Men_encrypt = bignum(25);
        console.log("r en funtion" +this.r);
        var e
         this.e = e;
        console.log("e en funtion" +e);
        return Men_encrypt.mul((this.r).powm(this.e,this.n));

         };

当我尝试访问主对象中的变量时,我得到的是它们是“Underfined”

1 个答案:

答案 0 :(得分:1)

假设您有以下内容:

rsa = {
    publicKey: function() {
        this.r = 5;
    }
}

要访问值r,您需要创建publicKey的实例,因此:

let key = new rsa.publicKey();
k.r; // 5

现在,您希望在blind的实例上使用rsa.publicKey方法,因此您需要使用blind方法设置对象作为rsa.publicKey的原型构造函数。你这样做:

rsa.publicKey.prototype = {
    blind() {
        console.log(this.r);
    }
}

现在你可以这样称呼它:

let key = new rsa.publicKey();
key.blind(); // outputs 5

它输出5因为this中的blind引用了key个对象,因为blind被称为key对象的方法。如果你喜欢这样:

rsa.publicKey.prototype.blind();

this引用rsa.publicKey.prototype对象,因为blind被称为rsa.publicKey.prototype的方法,并且它没有r属性。