【问题标题】:Why am I getting the error "is not a function" here? [duplicate]为什么我在这里收到错误“不是函数”? [复制]
【发布时间】:2017-01-10 10:00:54
【问题描述】:

我这里有一个 nodejs 问题,我真的不知道为什么会这样。

这是我的代码:

	isInTimeSlot() {
		return new Promise((resolve, reject) => {
			var date = new Date()
		    var hour = date.getHours()
		    hour = (hour < 10 ? "0" : "") + hour
		    var min  = date.getMinutes()
		    min = (min < 10 ? "0" : "") + min
		    if (hour >= this.followMinHour && hour <= this.followMaxHour) {
		    	return resolve(42)
		    } else if (hour >= this.unfollowMinHour && hour <= this.unfollowMaxHour) {
		    	return resolve(1337)
		    } else {
		    	return reject()
		    }
		})
	}

	checkProjectTimeSlot() {
		return new Promise((resolve, reject) => {
			var timer = setInterval(function() {
				console.log('Checking if bot is in time slot')
				this.isInTimeSlot()
				.then((mode) => {
					clearInterval(timer)
					resolve(mode)
				})
			}, 5000)		
		})
	}

所以这是我的ES6类的2个简单方法,当我执行它时,出现以下错误:

this.isInTimeSlot()
                     ^
TypeError: this.isInTimeSlot is not a function 

你能看到错误吗?

【问题讨论】:

  • 请为您的问题找到一个更好的标题...
  • 当您在 Promise 中时,this 不再指的是您所期望的。阅读this,你会修复它。
  • 可能this 所指的上下文与您认为的上下文不同。 WTF 亚历克斯!
  • 你没有使用箭头函数,所以 this 不是你想要的 this
  • 除了其他人已经告诉你的: 1. isInTimeSlot 不应该是一个承诺; 2. 你最好使用像moment.js 这样的用户库,而不是自己处理时间戳。

标签: javascript node.js


【解决方案1】:

当您处于承诺返回或计时器中时,您的 this 会发生变化。

isInTimeSlot() {
    return new Promise((resolve, reject) => {
        var date = new Date()
        var hour = date.getHours()
        hour = (hour < 10 ? "0" : "") + hour
        var min  = date.getMinutes()
        min = (min < 10 ? "0" : "") + min
        if (hour >= this.followMinHour && hour <= this.followMaxHour) {
            return resolve(42)
        } else if (hour >= this.unfollowMinHour && hour <= this.unfollowMaxHour) {
            return resolve(1337)
        } else {
            return reject()
        }
    })
}

checkProjectTimeSlot() {
    var that = this;
    return new Promise((resolve, reject) => {
        var timer = setInterval(function() {
            console.log('Checking if bot is in time slot')
            that.isInTimeSlot()
            .then((mode) => {
                clearInterval(timer)
                resolve(mode)
            })
        }, 5000)        
    })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    • 2019-10-14
    相关资源
    最近更新 更多