The following JavaScript code raises the exception below
var session = {
encoded : document.cookie.replace(/(?:(?:^|.*;\s*)session\s*\=\s*([^;]*).*$)|^.*$/, "$1"),
decoded : JSON.parse(atob(encoded))
}
Uncaught ReferenceError: encoded is not defined
If I append 'this' to encoded, then
var session = {
encoded : document.cookie.replace(/(?:(?:^|.*;\s*)session\s*\=\s*([^;]*).*$)|^.*$/, "$1"),
decoded : JSON.parse(atob(this.encoded))
}
Uncaught DOMException : Failed to execute 'atob' on 'Window'
Or if i append 'session', then
var session = {
encoded : document.cookie.replace(/(?:(?:^|.*;\s*)session\s*\=\s*([^;]*).*$)|^.*$/, "$1"),
decoded : JSON.parse(atob(session.encoded))
}
Uncaught TypeError: Cannot read property 'encoded' of undefined
What is the proper syntax to reference a member from another member? I understand that the 'this' keyword depends on where the code is being executed, but surely there is an intuitive way to reference this
EDIT
Here is a workaround just in-case anyone has the same problem (See accepted answer for explanation)
var session = {
encoded : function () { return document.cookie.replace(/(?:(?:^|.*;\s*)session\s*\=\s*([^;]*).*$)|^.*$/, "$1")},
decoded : function () { return JSON.parse(atob(this.encoded()))}
}