小知识(this/call/补零/节流/地址栏)

130 阅读1分钟

1.this指向

<script>
    var age = 50
    let obj = {
        age:20,
        sayHi(){
            console.log(this.age);
            return function(){
                console.log(this.age); 
            }                
        }
    }
    obj.sayHi()()   // 20  50
</script>

2. call和apply

<script>
    let arr1 = {
        length: 0,
        // push(val) {
        //     this[this.length] = val
        //     this.length++
        // },
        // forEach(fn) {
        //     for (let i = 0; i < this.length; i++) {
        //         fn(this[i], i)
        //     }
        // },
        push(val) {
            Array.prototype.push.call(this, val)
        },
        forEach(fn) {
            Array.prototype.forEach.call(this, fn)
        }
    }
    arr1.push('aaa')
    arr1.push('bbb')
    arr1.forEach(r => {
        console.log(r);
    })
</script>

3.补零

    repairZero(val) {
    return val < 10 ? ('0' + val) : val
    }

4.节流函数

    throttle(fn, wait) {
    let endTime = new Date
    return function () {
        if (new Date() - endTime < wait) return console.log('频繁了');
        fn.apply(this,arguments)
        endTime = new Date()
        }
    }

5.获取地址栏

    convertStr2Obj(str) {
    let obj = {};
    str.split('&').forEach(r => {
        let kv = r.split('=');
        let key = kv[0];
        let val = kv[1];
        obj[key] = decodeURI(val);
    })
    return obj
}
console.log(sun.convertStr2Obj(str1).name);