javascript 按给出的顺序,定义一个函数fn

按顺序输出:
实现fn:
1、fn(‘John’)
output: I am John
2、fn(‘John’).rest(10).learn(‘computer’)
output: I am John
// 等待10s:
Start learning after 10 seconds
Learning Computer
3、fn(‘John’).restFirst(5).learn(‘chinese’)
output:
// 等待5s
start learning after 5 seconds
I am John
Learing chinese

使用es6:class、 箭头函数

class fnName {
	constructor(name) {
	    this.name = name
		this.queue = []
		const fn = ()=> {
			console.log(`I am ${name}`)
			this.next()
		}
		debugger
		this.queue.push(fn)
		setTimeout(() => {
			this.next()
		}, 0)
	}
	rest (time) {
		const fn = () => {
			setTimeout(() => {
				console.log(`Start learning after ${time} ms`)
				this.next()
			}, time)
		}
		this.queue.push(fn)
		return this
	}
	learn (sub) {
		const fn = ()=> {
			console.log(`Learning ${sub}`)
			this.next()
		}
		this.queue.push(fn)
		return this
	}
	restFirst (time) {
		const fn = () => {
			setTimeout(() => {
				console.log(`Start learning after ${time} ms`)
				this.next()
			}, time)
		}
		this.queue.unshift(fn)
		return this
	}
	next () {
		const fn = this.queue.shift()
		fn && fn() 
	}
}
function fn(name) {
	return new fnName(name)
}

使用es5:

function fnClass (name) {
	_this = this
		this.name = name
		this.queue = []
		const fn = function () {
			console.log(`I am ${name}`)
			next()
		}
		next = function (){
			const fn = _this.queue.length > 0 ? _this.queue.shift() : null
			fn && fn.call(_this)
		}
		this.queue.push(fn)
		setTimeout(function (){
			next()
		}, 0)
		return _this
	}
	fnClass.prototype.rest = function (time) {
		const _this = this
		const fn = function () {
			setTimeout(function () {
				console.log(`Start learning after ${time} ms`)
				next.call(_this)
			}, time)
		}
		this.queue.push(fn)
		return this
	}
	fnClass.prototype.learn = function (sub) {
		const _this = this
		const fn = function() {
			console.log(`Learning ${sub}`)
			next.call(_this)
		}
		this.queue.push(fn)
		return this
	}
	function fn () {
		return new fnClass('John')
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值