-2

I am reading a React doc, https://reacttraining.com/react-router/web/example/auth-workflow, and trying to understand the following piece of code:

Looks like a the function definition happens in a json object, but my understanding is that we can't have funciton inside json

const fakeAuth = {
  isAuthenticated: false,
  authenticate(cb) {
    this.isAuthenticated = true;
    setTimeout(cb, 100); // fake async
  },
  signout(cb) {
    this.isAuthenticated = false;
    setTimeout(cb, 100);
  }
};
Prathibha
  • 199
  • 13
chen
  • 4,302
  • 6
  • 41
  • 70

3 Answers3

1

In true JSON you cannot have a function, and there are no vars. It's a format just used to hold data (based on JavaScript). You can have a function that is a property of an Object in JavaScript.

StackSlave
  • 10,613
  • 2
  • 18
  • 35
1

if you are referring to the whole const fakeAuth = {...} code, that is not a JSON object.. rather that is a creating a fakeAuth object has a property (isAuthenticated) and functions with parameters(authenticate, signout)

jmesolomon
  • 563
  • 5
  • 15
1

As mentioned in the comments, this isn't JSON, it's a Javascript object literal. It's using the ES6 shorthand syntax for function properties.

authenticate(cb) {
  this.isAuthenticated = true;
  setTimeout(cb, 100); // fake async
},

is short for:

authenticate: function(cb) {
  this.isAuthenticated = true;
  setTimeout(cb, 100); // fake async
},
Barmar
  • 741,623
  • 53
  • 500
  • 612