Javascript 访问原型中的主要对象变量
我有这个东西Javascript 访问原型中的主要对象变量,javascript,prototype,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
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
}
};
然后我有了这些对象的原型,如何从原型中访问对象中的变量
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));
};
当我尝试访问主对象中的变量时,我得到的结果是它们“定义不足”假设您有以下情况:
rsa = {
publicKey: function() {
this.r = 5;
}
}
要访问值r
,您需要创建一个publicKey
的实例,因此:
let key = new rsa.publicKey();
k.r; // 5
现在,您希望在rsa.publicKey
实例上有一个blind
方法可用,因此需要使用blind
方法将一个对象设置为rsa.publicKey
构造函数的原型。你是这样做的:
rsa.publicKey.prototype = {
blind() {
console.log(this.r);
}
}
let key = new rsa.publicKey();
key.blind(); // outputs 5
rsa.publicKey.prototype.blind();
现在你可以这样称呼它:
rsa.publicKey.prototype = {
blind() {
console.log(this.r);
}
}
let key = new rsa.publicKey();
key.blind(); // outputs 5
rsa.publicKey.prototype.blind();
它输出5
,因为这个在blind
中指的是key
对象,因为blind
被称为key
对象的一种方法。如果您喜欢这样做:
rsa.publicKey.prototype = {
blind() {
console.log(this.r);
}
}
let key = new rsa.publicKey();
key.blind(); // outputs 5
rsa.publicKey.prototype.blind();
此
指的是rsa.publicKey.prototype
对象,因为blind
被称为rsa.publicKey.prototype
,它没有r
属性。当我试图访问main-how?@Maximus中的变量时,例如从prototype中的blem-->this.r>的blind()中(要在publicKey:function()中获取this.r变量)您是这样调用它的rsa.publicKey.blind()
还是(new rsa.publicKey()).blind()
?我这样调用它:rsa.publicKey.prototype.blind();
在这种情况下,blind
在rsa.publicKey.prototype
对象的上下文中调用,该对象没有r
属性。您可能需要的是这个(新的rsa.publicKey()).blind()
-它应该能够访问r