JavaScript 笔试题(一)

222 阅读1分钟

1. this

var name = 'IU'

function a() {
    var name = 'Dami'
    console.log(this.name);
}

function d(i) {
    return i()
}
var b = {
    name: 'Wooshik',
    detail: function() {
        console.log(this.name);
    },
    bibi: function() {
        return function() {
            console.log(this.name);
        }
    }
}
var c = b.detail
b.a = a
var e = b.bibi()
a() // IU
c() // IU
b.a() // Wooshik
d(b.detail) // IU
e() // IU

2. 闭包

闭包:内部函数可以访问外部函数的作用域就是闭包。

(function autorun(){
    let x = 1;
    function log(){
      console.log(x);
    };
    
    function run(fn){
      let x = 100;
      fn();
    }
    
    run(log);//1
})();

闭包的外部作用域是在其定义的时候已决定,而不是执行的时候。

来源:
[译]发现 JavaScript 中闭包的强大威力

  • 面试题:
for (var i = 0; i < 5; i++) {
    setTimeout(function() {
        console.log(i++);
    }, 4000)
}
console.log(i);
// 输出:
// 5
// 5
// 6
// 7
// 8
// 9

怎么修改能输出5,0,1,2,3,4?
使用立即执行函数。

for (var i = 0; i < 5; i++) {
    (function(x) {
        setTimeout(function() {
            console.log(x++);
        }, 4000)
    })(i)

}
console.log(i);
// 输出:
// 5
// 0
// 1
// 2
// 3
// 4

3. 代码实现节流和防抖

节流:在delay时间段内只执行一次函数,在delay时间间隔内不管你点击多少次,函数都只执行一次。

// 方法1
function throttle(func, delay = 5000) {
    let timer
    return function() {
        let context = this
        let args = arguments
        if (timer) {
            return
        }
        setTimeout(() => {
            func.apply(context, args)
            timer = null
        }, delay)
    }
}
//方法2
function throttle(func, delay = 5000) {
    let pre = 0
    return function() {
        let now = new Date()
        let context = this
        let args = arguments
        if (now - pre > delay) {
            func.apply(context, args)
            pre = now
        }
    }
}

防抖:连续点击n次,以最后一次点击间隔delay时间后,执行函数;如果间隔时间小于delay,则计时器会重新计时。间隔时间满足delay才会执行一次函数。

function debounce(func, delay = 5000) {
    let timer
    return function() {
        let context = this
        let args = arguments
        clearInterval(timer)
        timer = setTimeout(() => {
            func.call(context, args)
        }, delay)
    }
}