0

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()))}
}
Michael
  • 177
  • 3
  • 11

1 Answers1

1

You cannot. Object creation must be fast, and therefore it cannot be unstable. If properties could access each other during creation, it could lead to problems. A workaround would be a temporary variable:

{
  const encoded = document.cookie.replace(/(?:(?:^|.*;\s*)session\s*\=\s*([^;]*).*$)|^.*$/, "$1");
  var session = {
    encoded,
    decoded : JSON.parse(atob(encoded))
  };
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • I see, i didn't realise that it was being evaluated during construction. That wasn't the behaviour i was looking for. I suppose i'd need to wrap them in functions to get them to evaluate each time i call a member – Michael Sep 03 '17 at 14:25