前端面试题

102 阅读1分钟

1、题目:

add(1).add(2).add(3) 等于6

2、分析

1、函数可以链式调用,那么函数执行完肯定要返回this才行
2、函数原型上必须add函数,才可使用.add

3、实现

function _add(num){
    this.sum = 0
    this.sum += num  
    return this
}
_add.prototype.add = function(num){
    this.sum += num
    return this
}
 function add(num){
     return new _add(num)
 }
let res = add(1).add(2).add(3)
console.log(res.sum); //6

4、思考

lazyMan('Lazy').eat('test').firstSleep(1).eat('apple').sleep(2).eat('orange')

// 1、注意必须在执行完firstSleep延迟时间后,才开始按顺序执行
// 2、 遇到sleep必须延迟后再继续执行后面的函数,

// 比如上面 demo输出结果为:

Lazy第一次睡觉

Lazy第一次睡醒了

我的名字是Lazy

Lazy正在吃app

Lazy正在吃apple

Lazy再次睡觉

Lazy再次睡醒

Lazy正在吃orange



作者:成都巴菲特
链接:www.zhihu.com/question/43…