简体   繁体   中英

How to get a property when setting others in Object Literal notation?

In java script I get this error

Uncaught ReferenceError: baseUrl is not defined 



window.Configurations = Configurations = {
        baseUrl: 'https://mysite.com/',
        detailsEventCustom: baseUrl + 'DetailsEventCustom?EventId=',
        addEventCustom: baseUrl + 'AddEventCustom',
        listAllEventsCustomForDate: baseUrl + 'ListAllEventsCustomForDate?DateToLookUp=',
        dashboardEventsCustom: baseUrl + 'DashboardEventsCustom',
        listAllTimetableEventsCustom: baseUrl + 'ListAllTimetableEventsCustom',
        updateEventCustom: baseUrl + 'UpdateEventCustom?EventId=',
        deleteEventCustom: baseUrl + 'DeleteEventCustom?EventId='
    };

Could you point me out what I am doing wrong here?

you cannot do it like this
when you are accessing the object hasn't been made try doing this instead

var baseUrl = 'https://mysite.com/';
window.Configurations = Configurations = {
        baseUrl: baseUrl,
        detailsEventCustom: baseUrl + 'DetailsEventCustom?EventId=',
        addEventCustom: baseUrl + 'AddEventCustom',
        listAllEventsCustomForDate: baseUrl + 'ListAllEventsCustomForDate?DateToLookUp=',
        dashboardEventsCustom: baseUrl + 'DashboardEventsCustom',
        listAllTimetableEventsCustom: baseUrl + 'ListAllTimetableEventsCustom',
        updateEventCustom: baseUrl + 'UpdateEventCustom?EventId=',
        deleteEventCustom: baseUrl + 'DeleteEventCustom?EventId='
    };

This is a scoping problem. You are still building the object between the curly braces, and all values are calculated before they are assigned to the object. baseUrl simply doesn't exist yet when you are using it to assign the other values. You should do something like this instead:

var baseUrl = 'https://mysite.com/'
window.Configurations = Configurations = {
    baseUrl: baseUrl,
    detailsEventCustom: baseUrl + 'DetailsEventCustom?EventId=',
    addEventCustom: baseUrl + 'AddEventCustom',
    listAllEventsCustomForDate: baseUrl + 'ListAllEventsCustomForDate?DateToLookUp=',
    dashboardEventsCustom: baseUrl + 'DashboardEventsCustom',
    listAllTimetableEventsCustom: baseUrl + 'ListAllTimetableEventsCustom',
    updateEventCustom: baseUrl + 'UpdateEventCustom?EventId=',
    deleteEventCustom: baseUrl + 'DeleteEventCustom?EventId='
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM