v2.5.2
Giriş yap

JavaScript objeler ve diziler

egemen
353 defa görüntülendi

merhabalar js'te classlar ile çalışırken bir yerde takıldım. bilmediğim bişey var fakat çözüm bulamadım.

    class Product {
    constructor(id, title, price, image, description, category) {
        this.id = id
        this.title = title
        this.price = price
        this.image = new URL(image,
            import.meta.url)
        this.description = description
        this.category = category
    }
}
class Products {
    constructor() {
        this.products = []
        this.fetchProducts()
    }
    fetchProducts() {
        fetch('https://fakestoreapi.com/products')
            .then(res => res.json())
            .then(json => {
                json.forEach(element => {
                    this.products.push(new Product(element.id, element.title, element.price, element.image, element.description, element.category))
                });
            })
    }
}

const test = new Products();

console.log(test.products[0]); // undefined
class Test {
    constructor(name, surname) {
        this.name = name
        this.surname = surname
    }
}
let arr = []
arr.push(new Test("name1", "surname1"))
arr.push(new Test("name2", "surname2"))
console.log(arr[0].name) // name1