手撕instanceof、new、原生ajax、深/浅拷贝、防抖/节流、call / apply / bind


手撕的步骤
(1)看要传什么参数
(2)看要返回什么
(3)实现中间部分的逻辑

1. 实现instanceof

第一个参数是实例,第二个参数是构造函数

function myInstanceof(instance, object) {
    let current = instance; //定义一个指针存储当前实例的位置
    let target = object.prototype; //存储目标构造函数的原型对象
    while (current) { //指针指向null时说明原型链上没这个构造函数
        if (current.__proto__ == target) { //如果找到了,就返回true
            return true;
        } else { //如果没找到,指针向后指
            current = current.__proto__
        }
    }
    //如果找到最后的null都没有,说明该实例不属于object所在原型链上任何一个原型对象
    return false;
}

测试代码:

console.log([1, 2, 3] instanceof Array); //true
console.log(myInstanceof([1, 2, 3], Array)) //true

console.log([1, 2, 3] instanceof Object); //true
console.log(myInstanceof([1, 2, 3], Object)); //true

console.log([1, 2, 3] instanceof Function); //false
console.log(myInstanceof([1, 2, 3], Function)); //false

console.log([1, 2, 3] instanceof RegExp); //false
console.log(myInstanceof(/1/, RegExp)); //true
2. 如何让 0.1+0.2 === 0.3
function withinError(left, right) {
    return Math.abs(left - right) < Number.EPSILON;
}
console.log(withinError(0.1 + 0.2, 0.3)); //true
3. 实现new关键字

第一个参数是构造函数,第二个参数是实例化传的参数

function myNew(Fn, ...args) {
    //1.判断传入的是否是一个函数
    if (typeof Fn != 'function') return false;
    //2.创建一个新对象,让该对象的__proto__指向构造函数的prototype
    const obj = Object.create(Fn.ptototype);
    //3.让Fn中的this指向这个新创建的对象,并给它们传值
    let result = Fn.call(obj, ...args);
    //4.如果构造函数写了返回值,要判断,如果是复杂数据类型,那么就返回该返回值
    if (result && (typeof result === 'object' || typeof result === 'function')) {
        return result;
    }
    //5.返回创建的新新对象(此时已经有了属性和原型对象中的方法)
    return obj;
}
4. 手写原生ajax
<body>
    <button>点击发送请求</button>
    <div id="result"></div>

    <script>
        //获取button元素
        const btn = document.querySelector('button');
        const result = document.querySelector('#result');
        btn.addEventListener('click', function() {
            //1.创建对象
            const xhr = new XMLHttpRequest();
            //2.初始化,设置请求的方法和url
            xhr.open('GET', 'http://127.0.0.1:8000/get-server?a=1&b=2&c=3');
            //3.发送
            xhr.send();

            //4.事件绑定,处理服务端返回的结果
            //on 当……的时候
            //readyState是xhr对象中的属性,表示状态0 1 2 3 4 
            //其中0-未初始化 1-open调用完毕 2-send调用完毕 3-服务端返回了部分结果 4-服务端返回了所有结果
            //change 改变
            xhr.onreadystatechange = function() {
                //判断服务端是否返回了所有结果
                if (xhr.readyState === 4) {
                    //判断响应状态码 200 404 403 401 500
                    // 2xx ,2开头都表示成功
                    if (xhr.status >= 200 && xhr.status < 300) {
                        //如果响应成功处理结果 行 头 空行 体
                        console.log('状态码:', xhr.status); //状态码
                        console.log('状态字符串:', xhr.statusText); //状态字符串
                        console.log('响应头:', xhr.getAllResponseHeaders()); //所有的响应头
                        console.log('响应体:', xhr.response); //响应体

                        //设置result文本
                        result.innerHTML = xhr.response;
                    }
                }
            }
        })
    </script>
</body>
5. 实现浅拷贝

参数是要拷贝的对象

function shallowCopy(object) {
    //如果传参数,或者参数不是数组或对象,那么就返回false
    if (!object || typeof object !== 'object') return false;
    //根据参数类型,判断新建一个数组还是新建一个对象
    let newObj = Array.isArray(object) ? [] : {};
    //遍历对象()或数组,并把object自身的可枚举属性(不包括原型上的属性)循环添加进去
    for (let key in object) {
        if (object.hasOwnPropery(key)) {
            newObj[key] = object[key];
        }
    }
}
6. 实现深拷贝

参数是要拷贝的对象。基本思路和浅拷贝一样,不同的是在拷贝时,如果遇到复杂数据类型,就要递归调用(再生成一个新的地址,把简单数据类型捞过来,返回新的地址,给到当前key),这样可以保证只要遇到复杂数据类型,都可以生成新的地址。

function deepCopy(obj) {
    //老样子,没传参或传的不是数组或对象,就return
    if (!obj || typeof obj !== 'object') return false;
    //根据类型创建新的地址
    let newObj = Array.isArray(obj) ? [] : {};
    //遍历obj,把属性和值偷过来
    for (let key in obj) {
        //如果属性值是数组或对象,就递归调用生成新的地址,递归出栈后把新地址给到当前key
        newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
    }
    //返回新地址
    return newObj;
}
7. 实现防抖

防抖的四个关键点

  • 调用防抖函数要返回一个函数,在函数中执行fn
  • 设置定时器,而且为了保证每次都清除上一个定时器,需要形成闭包(保证timer不被销毁)
  • this指向的问题,this应该指向绑定的DOM,但是定时器中调用指向的是window,我们要改变this指向
  • 调用的函数可能会传参(比如event),但是不好说传几个,用…args或arguments接收
<button>按钮</button>

初级版本:

function debounce(fn, delay) {
    let timer; //保存timer
    return function() {
        //第一次执行时,timer没有值,第二次执行有值就先销毁
        if(timer) clearTimeout(timer);
        timer = setTimeout(() => {
            fn();
        }, delay)
    }
}
let input = document.querySelector('input');
input.oninput = debounce(function() {
    console.log(this,input.value); //window
}, 1000)

改变this指向,接收可能传进来的参数:

function debounce(fn, delay) {
    let timer;
    return function(...args) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(this, args);
        }, delay)
    }
}
let input = document.querySelector('input');
input.oninput = debounce(function() {
    console.log(this, input.value); //window
}, 1000)
8. 实现节流

写法1:定时器

function throttle(fn, delay) {
    let timer;
    return function(...args) {
        if (timer) return; //如果timer已经开启了,就return
        timer = setTimeout(() => {
            fn.apply(this, args);
            timer = null; //时间到,执行一次,然后清空,再点击的时候再重新计时
        }, delay)
    }
}
window.onresize = throttle(function() {
    console.log('窗口大小改变');
}, 1000)

写法2:获取时间戳,第一次肯定会触发,因为new Date获取的是从1970年到现在的时间,delay总不能大于五十年吧……

function throttle(fn, delay) {
    let pre = 0; //设置初始时间,让这个变量不被销毁
    return function(...args) {
        let now = new Date(); //获取当前时间
        if (now - pre > delay) { //如果间隔触发时间大于延时时间,就执行函数
            fn.apply(this, args);
            pre = now; //执行完后,把当前时间给pre,用于下一次触发事件判断
        }
    }
}
window.onresize = throttle(function() {
    console.log('窗口大小改变');
}, 1000)
9. 实现call

思路:想想call的作用主要就是改变函数调用时的this指向,那么我们可以用一个很巧妙的方法隐式改变this指向:

  • 执行myCall时,作用域中this指向的一定是前面的函数(谁调用就指向谁)
  • 我们给context添加一个属性f为this(这个f最好是唯一的key,否则如果人家本来就有个key叫f呢?),调用这个属性,会隐式改变fn中this的指向(context调用它,那么它会指向context)
  • 最后删除这个属性,不能修改原本的context对象
  • 以上是主要的思路,还需要加入一些细节,比如传参
Function.prototype.myCall = function(context) {
    context = context || window; //如果没传第一个参数(传null),那么应该默认为window
    let args = [...arguments].slice(1);  //把传进来的其他参数在f调用时传给f
    //核心代码
    const f = Symbol();
    context[f] = this;
    let result = context[f](...args);  //函数要有返回值,要返回fn的返回值
    //delete context.f; //最后删掉该属性,因为原对象不能改变啊,如果用symbol可以不删?
    return result;
}
function fn(a,b) {
    console.log(this,a,b)
    return 'success';
}
let obj = {name: 'zqq'};
fn.myCall(obj,'参数1','参数2')

细节:

  • 如果第一个参数是null,那么应该给个判断
  • 函数应该有返回值,返回值应该就是fn的返回值
  • 调用myCall的必须是一个函数,否则就不对
10. 实现apply
Function.prototype.myApply = function(context) {
    context = context || window;
    let args = arguments[1]; 
    //如果传了第二个参数,但是传的不是数组,就报错
    if(args && !Array.isArray(args)) throw 'typeError';
    
    const f = Symbol();
    context[f] = this;
    //如果传了第二个参数,那么就解构,否则只改变this指向
    let result = args ? context[f](...args) : context[f]();
    //delete context.f;
    return result;
}
function fn(a,b) {
    console.log(this,a,b);
    return 'success';
}
let obj = {age: 18};
fn.myApply(obj, ['参数1','参数2']);
11. 实现bind

返回一个函数,调用这个函数的时候就调用myBind的调用者,并改变this

但是要考虑构造函数的情况,这里以myPerson命名方便理解

Function.prototype.myBind = function(context, ...args) {
    let _this = this; //保存调用者
    //返回一个函数,而且函数中this是指向context的
    return function myPerson(...args2) {
        //这里要考虑构造函数的情况,调用myPerson返回的是一个实例,那么应该让Person中的this指向
        //myPerson的实例(也就是本函数中的this),也就是person
        return _this.apply(this instanceof myPerson ? this : context, [...args, ...args2])
    }
}
function Person(a, b) {
    console.log(this, a, b)
    return 'success';
}
let obj = {
    name: 'zqq'
};
let myPerson = Person.myCall(obj, '参数1', '参数2')
let person = new myPerson();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值