实例数组变得无法访问范围

时间:2018-06-17 16:14:26

标签: javascript node.js electron

我首先宣布了一类药物:

// Classes

// __Drug
class Drug {

    constructor(id, name, form, ppv, stock) {
        this.id = id
        this.name = name
        this.form = form
        this.ppv = ppv
        this.stock = stock
    }

}

接下来,我有一类搜索:

// __Search
class Search {

    constructor(query = null) {
        this.query = query
        this.results = []
    }

    // Searches for the query in the database and limits the search results
    forQuery(limit = 10) {
        let sqlQuery = `SELECT db_drug_id, db_drug_name, db_drug_form,  db_drug_ppv, db_drug_stock FROM drugs WHERE db_drug_name LIKE "${this.query}%" LIMIT ${limit}`
        connection.query(sqlQuery, (errors, results) => {
            if (errors) throw errors
            for (let i in results) {
                this["results"].push(new Drug(results[i].db_drug_id, results[i].db_drug_name, results[i].db_drug_form, results[i].db_drug_ppv, results[i].db_drug_stock))
            }
            console.log(this.results) // This logs after the second console.log
        })
        console.log(this.results)
    }

}

在connection.query中,console.log(this.results)记录:

enter image description here

Next second console.log(this.results)日志: enter image description here

我无法使用this.results [i]访问它的内容。我希望创建另一种方法将这些结果附加到DOM。在定义它时,我将面临无法访问它的问题。我无法从搜索实例中访问它。

这就是我所说的方法。

// Document
$(document).ready(function() {

    // Listens for any change in the search input field
    $('#search-input').on('input', function() { 
        search = new Search($("#search-input").val())
        search.forQuery(10)
    })

})

0 个答案:

没有答案