Home  >  Q&A  >  body text

JS: How to build an object based on parent properties

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粉883223328P粉883223328178 days ago1417

reply all(1)I'll reply

  • P粉432930081

    P粉4329300812024-04-05 13:13:09

    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();
    

    reply
    0
  • Cancelreply