ES6类方法不仅仅是在一种方法上发生的功能

时间:2017-12-12 02:26:10

标签: javascript oop object

我正在尝试采用更多OOP方法来编写Javascript。作为一个相对初学者,我对我得到的错误Uncaught TypeError: this.getCoinSelOption is not a function at getBTC感到有点困惑。我有这个关键字调用我的类中的其他方法,但它不希望在一个间隔调用不同的方法。我该怎么办?

我如何打电话:

coins.getBTC(abbr)
setInterval(coins.getBTC, 10000)

我最初可以调用该方法,但是当我需要重新确定BitCoin的缩写时,我会转到全局const abbr并根据通过select标签选择的内容更新值

class Coins {
    constructor () {
        this.coinOptions = document.getElementById('coinOptions');
    }
    getCoinObjects (url) {
        let promise = new Promise((resolve, reject) => {
           fetch(url)
            .then(response => {
                resolve(response.json().then(data => {
                    let coins = []
                    for (var key in data.Data) {
                        coins.push(data.Data[key])
                    }
                    //this is working here!
                    this.getCoinOptions(coins)
                    return coins
                }))
            })
            .catch(response => {
               reject('“Api call failed!”')
            })
          })
        .then(response => {
            return coins
        })
        .catch(response => {
            console.log('error: ' + response)
        })
    }

    getCoinOptions(keys) {
        for (var i = 0; i < keys.length; i++) {
            var opt = document.createElement('option');
            opt.value = keys[i].Symbol
            opt.innerHTML = keys[i].CoinName
            this.coinOptions.appendChild(opt)
        }
    }

    getBTC(abbr) {
        if (abbr === undefined) {
            //this not working here
            abbr = this.getCoinSelOption(this.coinOptions)
            console.log('this is the abbr' + abbr)
        }

        axios.get('https://min-api.cryptocompare.com/data/pricemulti?fsyms='+abbr+'&tsyms=USD')
            .then(res => {
                console.log(abbr)
                const cryptos = res.data[abbr].USD
                price.innerHTML = '$'+cryptos.toLocaleString('en')

                if (targetPrice.innerHTML != '' && targetPriceVal < res.data[abbr].USD) {
                    const myNotification = new window.Notification(notification.title, notification)
                }
                return abbr
            })
        setTimeout(this.getBTC, 10000)
    }

    getCoinSelOption(sel) {
        console.log('called')
        loadBounce.classList.add('loading')
        this.getBTC(sel.options[sel.selectedIndex].value)
        setTimeout(function() {
            loadBounce.classList.remove('loading')
        }, 900)
        return sel.options[sel.selectedIndex].value
    }

}

0 个答案:

没有答案