A
A
Ankozar2021-04-30 07:02:58
JavaScript
Ankozar, 2021-04-30 07:02:58

Why is there json in the object, but you can't access it?

class Json {
    constructor(filename){
        this.filename = filename,
        this.json
    }
    getJson = () =>{
        let xhr = new XMLHttpRequest()
            xhr.open('GET', this.filename + '.json')
            xhr.responseType = 'json'
            xhr.send()
            xhr.onload = ()=>{
                if(xhr.status == 200){
                    this.json = xhr.response
                    }else{
                    console.log(xhr.status)
                }
            }
    }
   
}

const tagsObj = new Json('tags')
tagsObj.getJson()
console.log(tagsObj) //выводит  объект со свойством json
console.log(tagsObj.json) //говорит что свойство json undefined


Here's the output:
608b80da2c657891641006.jpeg

Why is that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lynn "Coffee Man", 2021-04-30
@Ankozar

Because it is not there yet at the time of the appeal.
Hover your mouse over the blue i in the screenshot.
Read about asynchrony before enlightenment.
UPD: the most linked question on ruSO https://ru.stackoverflow.com/a/554337/190728

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question