Search code examples
javascriptobjectthis

How to access an object from an object nested function with this keyword?


I have this object:

popup_data = {
    club: {
        type: 'club',
        type_img: {
            header: 'CLUB HEADER',
            img: 'https://source.unsplash.com/random/800x600',
            sub_header: 'CLUB SUB HEADER',
            content: 'TEXT',
            hotspot_position: [5, -1.5, 2.5]
        },
        hotspots_array: [
            {   id: () => this.club.type + '-' + 'type_img',
                position: () => this.club.type_img.hotspot_position,
            },
        ]   
    },

How to get type and type_img.hotspot_position from these nested functions


Solution

  • just use the var name, popup_data

    popup_data = {
        club: {
            type: 'club',
            type_img: {
                header: 'CLUB HEADER',
                img: 'https://source.unsplash.com/random/800x600',
                sub_header: 'CLUB SUB HEADER',
                content: 'TEXT',
                hotspot_position: [5, -1.5, 2.5]
            },
            hotspots_array: [
                {   id: () => popup_data.club.type + '-' + 'type_img',
                    position: () => popup_data.club.type_img.hotspot_position,
                },
            ]   
        },
    

    Read This and This

    What is this?
    In JavaScript, the this keyword refers to an object.

    Which object depends on how this is being invoked (used or called).

    The this keyword refers to different objects depending on how it is used:

    In an object method, this refers to the object.
    Alone, this refers to the global object.
    In a function, this refers to the global object.
    In a function, in strict mode, this is undefined.
    In an event, this refers to the element that received the event.
    Methods like call(), apply(), and bind() can refer this to any object.