JS: How to build an object based on parent properties
P粉883223328
P粉883223328 2024-04-04 21:08:50
0
1
1539

I'm trying to create a JS object that contains all URLs.

I want to achieve this through the data() part:

export default defineComponent({
  name: 'MyPage',
  data() {
    backendUrls: {...}
  }
})

Looking at it in a simpler way, it would look like this:

backendUrls: {
  baseUrl: "http://localhost:8080",
  baseUrlWithPrefix: function() { return this.baseUrl + "/ver1"; }
  userAdd: function() { return this.baseUrlWithPrefix() + "/user/add"; }
}

I can use the this keyword because it points to the same object as the one where the given property is located.

But I want to split it again and create objects within objects:

backendUrls: {
  baseUrl: "http://localhost:8080",
  generalUrls: {
    baseUrlWithPrefix: ...
  },
  socketUrls: {
    messageUrls: {
      userAdd: ...
    }
  }
}

Here, if I try generalUrls: { baseUrlWithPrefix: function() { return this.baseUrl "/ver1"; }}, it won't work because it can't find baseUrl, because the this keyword points to the generalUrls object, not the backendUrls object, in which baseUrl exists.

I need something like this:

backendUrls: {
  baseUrl: "http://localhost:8080",
  generalUrls: {
    baseUrlWithPrefix: function() { return {goBackToParentObject}.this.baseUrl + "/ver1"; }
  },
  socketUrls: {
    messageUrls: {
      userAdd: function() { return {goBackToParentObject}.this.generalUrls.baseUrlWithPrefix() + "/user/add"; }
    }
  }
}

P粉883223328
P粉883223328

reply all(1)
P粉432930081

Just change the way you call the function as follows

const backendUrls = {
  baseUrl: "http://localhost:8080",
  generalUrls: {
    baseUrlWithPrefix: function() { return this.baseUrl + "/ver1"; }
  },
}

const example = backendUrls.generalUrls.baseUrlWithPrefix.bind(backendUrls);

example();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template