Reputation: 173
Base64.js
var Base64 = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
encode: function(e) {
var t = "";
var n, r, i, s, o, u, a;
var f = 0;
e = Base64._utf8_encode(e);
while (f < e.length) {
n = e.charCodeAt(f++);
r = e.charCodeAt(f++);
i = e.charCodeAt(f++);
s = n >> 2;
o = (n & 3) << 4 | r >> 4;
u = (r & 15) << 2 | i >> 6;
a = i & 63;
if (isNaN(r)) {
u = a = 64
} else if (isNaN(i)) {
a = 64
}
t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
}
return t
}
}
I am calling encode method from another file like below
had imported base64.js
file and created object
Var base64=new Base64.encode(input);
Error:
Uncaught Type error: undefined is not a function
Can any one help?
Upvotes: 0
Views: 233
Reputation: 24925
Var
should be var
_utf8_encode
is not defined.var encodedStr = Base64.encode(input)
In this line
t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
in your original code, this
refers to the object created by new
, not Base64
, so this._keyStr
is undefined
. But if you directly call Base64.encode()
(#3 above), it will refer to Base64
and you will get proper values.
var Base64 = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
encode: function(e) {
var t = "";
var n, r, i, s, o, u, a;
var f = 0;
e = Base64._utf8_encode(e);
while (f < e.length) {
n = e.charCodeAt(f++);
r = e.charCodeAt(f++);
i = e.charCodeAt(f++);
s = n >> 2;
o = (n & 3) << 4 | r >> 4;
u = (r & 15) << 2 | i >> 6;
a = i & 63;
if (isNaN(r)) {
u = a = 64
} else if (isNaN(i)) {
a = 64
}
t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
}
return t
},
_utf8_encode: function(e) {
// do your processing
return e
}
}
var input = "Hello World";
var base64 = Base64.encode(input);
console.log(base64)
Note: I have defined _utf8_encode
, but it returns same text. Please add necessary code.
Upvotes: 1