Etienne Noël
Etienne Noël

Reputation: 6166

Javascript - Object in object access first parent's property

I have an object inside another object and I need to access the first parent's property. Here is my code.

var api = {

    apiBaseUrl: 'http://example.com/',

    sendRequest: function (url, method, data) {
        console.log('send request')
        $.ajax({
            url: 'url',
            type: method,
            data: data
        })
    },

    /**
     * string topic, function callback
     */
    study: {
        getStudies: function () {
            var url = this.apiBaseUrl + 'studies';
            var method = 'GET';

            this.sendRequest(url, method);
        },
    };
};

api.study.getStudies()

In the function api.study.getStudies(), I want to acccess the variable apiBaseUrl and the function sendRequest of the api object, how can I do that ?

Upvotes: 1

Views: 45

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074989

With what you've quoted, you only have a single object, so just use api where you currently have this. As the functions are closures over the context containing the api variable, they have access to the variable.

Note that the quoted code also has a syntax error.

So the changes are:

study: {
    getStudies: function () {
        var url = api.apiBaseUrl + 'studies'; // <== Here
        var method = 'GET';

        api.sendRequest(url, method);         // <== Here
    },
}                                             // <== Here (the ; was a syntax error)

Upvotes: 2

Related Questions