• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

14道高频编写JS面试题和答案,巩固你的JS基础

武飞扬头像
YinJie…
帮助1

目录

1. 手写深拷贝

2. 防抖函数

3. 节流函数

4. 模拟 instanceof

5. 全局通用的数据类型判断方法

6. 手写 call 函数

7. 手写 apply 函数

8. bind方法

9. 模拟 new 

10. 类数组转化为数组的方法

11. 组合继承

12. 原型式继承

13. 实现 Object.create()

14. 数组去重


1. 手写深拷贝

  1.  
    function deepClone(startObj,endObj) {
  2.  
    let obj = endObj || {}
  3.  
    for (let i in startObj) {
  4.  
    if (typeof startObj[i] === 'object') {
  5.  
    startObj[i].constructor === Array ? obj[i] = [] : obj[i] = {}
  6.  
    deepClone(startObj[i],obj[i])
  7.  
    } else {
  8.  
    obj[i] = startObj[i]
  9.  
    }
  10.  
    }
  11.  
    return obj
  12.  
    }

值得注意的一点是,在递归调用的时候,需要把当前处理的 obj[i] 给传回去,否则的话 每次递归obj都会被赋值为空对象,就会对已经克隆好的数据产生影响。 

我们验证一下深拷贝是否实现:

  1.  
    const person = {
  2.  
    name: 'zyj',
  3.  
    age: 20,
  4.  
    sister: {
  5.  
    name: 'duoduo',
  6.  
    age: 13,
  7.  
    mother: {
  8.  
    name: 'lili',
  9.  
    age:45
  10.  
    }
  11.  
    }
  12.  
    }
  13.  
    const newPerson = deepClone(person)
  14.  
    newPerson.sister.mother.age = 50
  15.  
    console.log(newPerson)
  16.  
    // {
  17.  
    // name: 'zyj',
  18.  
    // age: 20,
  19.  
    // sister: { name: 'duoduo', age: 13, mother: { name: 'lili', age: 50 } }
  20.  
    // }
  21.  
    console.log(person)
  22.  
    // {
  23.  
    // name: 'zyj',
  24.  
    // age: 20,
  25.  
    // sister: { name: 'duoduo', age: 13, mother: { name: 'lili', age: 45 } }
  26.  
    // }
学新通

2. 防抖函数

单位时间内,频繁触发一个事件,以最后一次触发为准。

  1.  
    function debounce(fn,delay) {
  2.  
    let timer = null
  3.  
    return function() {
  4.  
    clearTimeout(timer)
  5.  
    timer = setTimeout(() => {
  6.  
    fn.call(this)
  7.  
    }, delay);
  8.  
    }
  9.  
    }

我们看一下调用流程:

  1.  
    <body>
  2.  
    <input type="text">
  3.  
    <script>
  4.  
    const input = document.querySelector('input')
  5.  
    input.addEventListener('input',debounce(function() {
  6.  
    console.log(111);
  7.  
    },1000))
  8.  
    function debounce(fn,delay) {
  9.  
    let timer = null
  10.  
    return function() {
  11.  
    clearTimeout(timer)
  12.  
    timer = setTimeout(() => {
  13.  
    fn.call(this)
  14.  
    }, delay);
  15.  
    }
  16.  
    }
  17.  
    </script>
  18.  
    </body>
学新通

可能有些同学对 fn.call(this) 不太明白,在 debounce 中我们把匿名函数作为参数传进来,因为匿名函数的执行环境具有全局性,所以它的 this 一般指向 window ,所以要改变一下 this 指向,让它指向调用者 input 。

3. 节流函数

单位时间内,频繁触发一个事件,只会触发一次。

  1.  
    function throttle(fn,delay) {
  2.  
    return function () {
  3.  
    if (fn.t) return;//每次触发事件时,如果当前有等待执行的延时函数,则直接return
  4.  
    fn.t = setTimeout(() => {
  5.  
    fn.call(this);//确保执行函数中this指向事件源,而不是window
  6.  
    fn.t = null//执行完后设置 fn.t 为空,这样就能再次开启新的定时器
  7.  
    }, delay);
  8.  
    };
  9.  
    }

调用流程:

  1.  
    <script>
  2.  
    //节流throttle代码:
  3.  
    function throttle(fn,delay) {
  4.  
    return function () {
  5.  
    if (fn.t) return;//每次触发事件时,如果当前有等待执行的延时函数,则直接return
  6.  
    fn.t = setTimeout(() => {
  7.  
    fn.call(this);//确保执行函数中this指向事件源,而不是window
  8.  
    fn.t = null//执行完后设置 fn.t 为空,这样就能再次开启新的定时器
  9.  
    }, delay);
  10.  
    };
  11.  
    }
  12.  
    window.addEventListener('resize', throttle(function() {
  13.  
    console.log(11);
  14.  
    },1000));
  15.  
    </script>
学新通

只有当调整浏览器视口大小时才会输出,且每隔一秒输出一次

4. 模拟 instanceof

  1.  
    // 模拟 instanceof
  2.  
    function myInstance(L, R) {
  3.  
    //L 表示左表达式,R 表示右表达式
  4.  
    let RP = R.prototype; // 取 R 的显示原型
  5.  
    let LP = L.__proto__; // 取 L 的隐式原型
  6.  
    while (true) {
  7.  
    if (LP === null) return false;
  8.  
    if (RP === LP)
  9.  
    // 这里重点:当 O 严格等于 L 时,返回 true
  10.  
    return true;
  11.  
    LP = LP.__proto__;
  12.  
    }
  13.  
    }
  1.  
    function person(name) {
  2.  
    this.name = name
  3.  
    }
  4.  
    const zyj = new person('库里')
  5.  
     
  6.  
    console.log(myInstance(zyj,person)); // true

5. 全局通用的数据类型判断方法

  1.  
    function getType(obj){
  2.  
    let type = typeof obj;
  3.  
    if (type !== "object") { // 先进行typeof判断,如果是基础数据类型,直接返回
  4.  
    return type;
  5.  
    }
  6.  
    // 对于typeof返回结果是object的,再进行如下的判断,正则返回结果
  7.  
    return Object.prototype.toString.call(obj).replace(/^\[object (\S )\]$/, '$1'); // 注意正则中间有个空格
  8.  
    }

6. 手写 call 函数

  1.  
    Function.prototype.myCall = function (context) {
  2.  
    // 先判断调用myCall是不是一个函数
  3.  
    // 这里的this就是调用myCall的
  4.  
    if (typeof this !== 'function') {
  5.  
    throw new TypeError("Not a Function")
  6.  
    }
  7.  
     
  8.  
    // 不传参数默认为window
  9.  
    context = context || window
  10.  
     
  11.  
    // 保存this
  12.  
    context.fn = this
  13.  
     
  14.  
    // 保存参数
  15.  
    let args = Array.from(arguments).slice(1)
  16.  
    //Array.from 把伪数组对象转为数组,然后调用 slice 方法,去掉第一个参数
  17.  
     
  18.  
    // 调用函数
  19.  
    let result = context.fn(...args)
  20.  
     
  21.  
    delete context.fn
  22.  
     
  23.  
    return result
  24.  
     
  25.  
    }
学新通

7. 手写 apply 函数

  1.  
    Function.prototype.myApply = function (context) {
  2.  
    // 判断this是不是函数
  3.  
    if (typeof this !== "function") {
  4.  
    throw new TypeError("Not a Function")
  5.  
    }
  6.  
     
  7.  
    let result
  8.  
     
  9.  
    // 默认是window
  10.  
    context = context || window
  11.  
     
  12.  
    // 保存this
  13.  
    context.fn = this
  14.  
     
  15.  
    // 是否传参
  16.  
    if (arguments[1]) {
  17.  
    result = context.fn(...arguments[1])
  18.  
    } else {
  19.  
    result = context.fn()
  20.  
    }
  21.  
    delete context.fn
  22.  
     
  23.  
    return result
  24.  
    }
  25.  
     
学新通

8. bind方法

在实现手写bind方法的过程中,看了许多篇文章,答案给的都很统一,准确,但是不知其所以然,所以我们就好好剖析一下bind方法的实现过程。

我们先看一下bind函数做了什么:

bind() 方法会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数。

读到这里我们就发现,他和 apply , call 是不是很像,所以这里指定 this 功能,就可以借助 apply 去实现:

  1.  
    Function.prototype.myBind = function (context) {
  2.  
    // 这里的 this/self 指的是需要进行绑定的函数本身,比如用例中的 man
  3.  
    const self = this;
  4.  
    // 获取 myBind 函数从第二个参数到最后一个参数(第一个参数是 context)
  5.  
    // 这里产生了闭包
  6.  
    const args = Array.from(arguments).slice(1)
  7.  
    return function () {
  8.  
    // 这个时候的 arguments 是指 myBind 返回的函数传入的参数
  9.  
    const bindArgs = Array.from(arguments)
  10.  
    // 合并
  11.  
    return self.apply(context, args.concat(bindArgs));
  12.  
    };
  13.  
    };

大家对这段代码应该都能看懂,实现原理和手写 call , apply 都很像,因为 bind 可以通过返回的函数传参,所以在 return 里面获取的 bindArgs 就是这个意思,然后最后通过 concat 把原来的参数和后来传进来的参数进行数组合并。

我们来看一下结果:

  1.  
    const person = {
  2.  
    name: 'zyj'
  3.  
    }
  4.  
     
  5.  
    function man(age) {
  6.  
    console.log(this.name);
  7.  
    console.log(age)
  8.  
    }
  9.  
     
  10.  
    const test = man.myBind(person)
  11.  
    test(18)//zyj 18

现在重点来了,bind 区别于 call 和 apply 的地方在于它可以返回一个函数,然后把这个函数当作构造函数通过 new 操作符来创建对象。

我们来试一下:

  1.  
    const person = {
  2.  
    name: 'zyj'
  3.  
    }
  4.  
     
  5.  
    function man(age) {
  6.  
    console.log(this.name);
  7.  
    console.log(age)
  8.  
    }
  9.  
     
  10.  
    const test = man.myBind(person)
  11.  
    const newTest = new test(18) // zyj 18

这是用的我们上面写的 myBind 函数是这个结果,那原生 bind 呢?

  1.  
    const person = {
  2.  
    name: 'zyj'
  3.  
    }
  4.  
     
  5.  
    function man(age) {
  6.  
    console.log(this.name);
  7.  
    console.log(age)
  8.  
    }
  9.  
     
  10.  
    const test = man.bind(person)
  11.  
    const newTest = new test(18) // undefined 18

由上述代码可见,使用原生 bind 生成绑定函数后,通过 new 操作符调用该函数时,this.name 是一个 undefined,这其实很好理解,因为我们 new 了一个新的实例,那么构造函数里的 this 肯定指向的就是实例,而我们的代码逻辑中指向的始终都是 context ,也就是传进去的参数。

所以现在我们要加个判断逻辑:

  1.  
    Function.prototype.myBind = function (context) {
  2.  
    // 这里的 this/self 指的是需要进行绑定的函数本身,比如用例中的 man
  3.  
    const self = this;
  4.  
    // 获取 myBind 函数从第二个参数到最后一个参数(第一个参数是 context)
  5.  
    // 这里产生了闭包
  6.  
    const args = Array.from(arguments).slice(1)
  7.  
    const theBind = function () {
  8.  
    const bindArgs = Array.from(arguments);
  9.  
     
  10.  
    // 当绑定函数作为构造函数时,其内部的 this 应该指向实例,此时需要更改绑定函数的 this 为实例
  11.  
    // 当作为普通函数时,将绑定函数的 this 指向 context 即可
  12.  
    // this instanceof fBound 的 this 就是绑定函数的调用者
  13.  
    return self.apply(
  14.  
    this instanceof theBind ? this : context,
  15.  
    args.concat(bindArgs)
  16.  
    );
  17.  
    };
  18.  
    return theBind;
  19.  
    };
学新通

现在这个效果我们也实现了,那我们的 myBind 函数就和其他的原生 bind 一样了吗?来看下面的代码:

  1.  
    const person = {
  2.  
    name: 'zyj'
  3.  
    }
  4.  
    function man(age) {
  5.  
    console.log(this.name);
  6.  
    console.log(age)
  7.  
    }
  8.  
    man.prototype.sayHi = function() {
  9.  
    console.log('hello')
  10.  
    }
  11.  
    const test = man.myBind(person)
  12.  
    const newTest = new test(18) // undefined 18
  13.  
    newTest.sayHi()

如果 newTest 是我们 new 出来的 man 实例,那根据原型链的知识,定义在man的原型对象上的方法肯定会被继承下来,所以我们通过 newTest.sayHi 调用能正常输出 hello 么?

学新通

该版代码的改进思路在于,将返回的绑定函数的原型对象的 __proto__ 属性,修改为原函数的原型对象。便可满足原有的继承关系。

  1.  
    Function.prototype.myBind = function (context) {
  2.  
    // 这里的 this/self 指的是需要进行绑定的函数本身,比如用例中的 man
  3.  
    const self = this;
  4.  
    // 获取 myBind 函数从第二个参数到最后一个参数(第一个参数是 context)
  5.  
    // 这里产生了闭包
  6.  
    const args = Array.from(arguments).slice(1);
  7.  
    const theBind = function () {
  8.  
    const bindArgs = Array.from(arguments);
  9.  
     
  10.  
    // 当绑定函数作为构造函数时,其内部的 this 应该指向实例,此时需要更改绑定函数的 this 为实例
  11.  
    // 当作为普通函数时,将绑定函数的 this 指向 context 即可
  12.  
    // this instanceof fBound 的 this 就是绑定函数的调用者
  13.  
    return self.apply(
  14.  
    this instanceof theBind ? this : context,
  15.  
    args.concat(bindArgs)
  16.  
    );
  17.  
    };
  18.  
    theBind.prototype = Object.create(self.prototype)
  19.  
    return theBind;
  20.  
    };
学新通

9. 模拟 new 

  1.  
    // 手写一个new
  2.  
    function myNew(fn, ...args) {
  3.  
    // 创建一个空对象
  4.  
    let obj = {}
  5.  
    // 使空对象的隐式原型指向原函数的显式原型
  6.  
    obj.__proto__ = fn.prototype
  7.  
    // this指向obj
  8.  
    let result = fn.apply(obj, args)
  9.  
    // 返回
  10.  
    return result instanceof Object ? result : obj
  11.  
    }

有很多小伙伴不明白为什么要判断 result 是不是 Object  的实例,我们首先得了解,在JavaScript中构造函数可以有返回值也可以没有。

1. 没有返回值的情况返回实例化的对象

  1.  
    function Person(name, age){
  2.  
    this.name = name
  3.  
    this.age = age
  4.  
    }
  5.  
    console.log(Person()); //undefined
  6.  
    console.log(new Person('zyj',20));//Person { name: 'zyj', age: 20 }

2. 如果存在返回值则检查其返回值是否为引用类型,如果为非引用类型,如(string,number,boolean,null,undefined),上述几种类型的情况与没有返回值的情况相同,实际返回实例化的对象

  1.  
    function Person(name, age){
  2.  
    this.name = name
  3.  
    this.age = age
  4.  
    return 'lalala'
  5.  
    }
  6.  
    console.log(Person()); //lalala
  7.  
    console.log(new Person('zyj',20));//Person { name: 'zyj', age: 20 }

3. 如果存在返回值是引用类型,则实际返回该引用类型

  1.  
    function Person(name, age){
  2.  
    this.name = name
  3.  
    this.age = age
  4.  
    return {
  5.  
    name: 'curry',
  6.  
    ahe: 34
  7.  
    }
  8.  
    }
  9.  
    console.log(Person()); //{ name: 'curry', ahe: 34 }
  10.  
    console.log(new Person('zyj',20));//{ name: 'curry', ahe: 34 }

10. 类数组转化为数组的方法

  1.  
    const arrayLike=document.querySelectorAll('div')
  2.  
     
  3.  
    // 1.扩展运算符
  4.  
    [...arrayLike]
  5.  
    // 2.Array.from
  6.  
    Array.from(arrayLike)
  7.  
    // 3.Array.prototype.slice
  8.  
    Array.prototype.slice.call(arrayLike)
  9.  
    // 4.Array.apply
  10.  
    Array.apply(null, arrayLike)
  11.  
    // 5.Array.prototype.concat
  12.  
    Array.prototype.concat.apply([], arrayLike)

11. 组合继承

  1.  
    function father (name) {
  2.  
    this.name = name
  3.  
    this.age = 18
  4.  
    }
  5.  
     
  6.  
    father.prototype.getName = function(){} // 方法定义在父类原型上(公共区域)
  7.  
     
  8.  
    function child () {
  9.  
    // 继承父类属性,可传入参数
  10.  
    father.call(this,'Tom')
  11.  
    // 将会生成如下属性:
  12.  
    // name:'tom'
  13.  
    // age: 18
  14.  
    }
  15.  
    child.prototype = new father() // 重写原型对象
  16.  
    child.prototype.constructor = child
学新通

这里的原型链关系应该是这样的:

学新通该方式也叫做伪经典继承。其核心思路是:重写子类的原型对象为父类实例,并通过盗用构造函数继承父类实例的属性。

12. 原型式继承

基本思路是,对传入的对象做了一次浅复制,并赋值给一个空函数 F (临时类型)的原型对象,并返回一个通过 F 生成的实例。这个实例的 __proto__ 自然而然地指向了传入的对象,可以理解为一个挂钩🧷的过程。

  1.  
    function object(o) {
  2.  
    function F() {}
  3.  
    F.prototype = o;
  4.  
    return new F();
  5.  
    }
  6.  
     
  7.  
    let father = function() {}
  8.  
    father.prototype.getName = function() {
  9.  
    console.log('zyj')
  10.  
    }
  11.  
     
  12.  
    let son = object(father)
  13.  
    let daughter = object(father)
  14.  
    son.prototype.getName() // zyj

大概是这么个过程:

学新通

ECMAScript 5 中,通过增加 Object.create() 方法将原型式继承的概念规范化,即替代了上述自定义的 object() 函数。所以对于 Object.create() 的手写实现,核心思路与上述的自定义函数类似,只是添加了部分参数校验的环节。

let son = Object.create(father)  // 等同于上述代码

13. 实现 Object.create()

  1.  
    Object.myCreate = function(proto, propertyObject) {
  2.  
    // 参数校验
  3.  
    if (typeof proto !== 'object' && typeof proto !== 'function') {
  4.  
    throw new TypeError('Object prototype may only be an Object or null.')
  5.  
    // 不能传一个 null 值给实例作为属性
  6.  
    if (propertyObject == null) {
  7.  
    new TypeError('Cannot convert undefined or null to object')
  8.  
    }
  9.  
    // 原型式继承的思想:用一个空函数(即忽略掉原有构造函数的初始化代码)创建一个干净的实例
  10.  
    function F() {}
  11.  
    F.prototype = proto // 确定后续的继承关系
  12.  
    const obj = new F()
  13.  
     
  14.  
    // 如果有传入第二个参数,将其设为 obj 的属性
  15.  
    if (propertyObject != undefined) {
  16.  
    Object.defineProperties(obj, propertyObject)
  17.  
    }
  18.  
     
  19.  
    // 即 Object.create(null) 创建一个没有原型对象的对象
  20.  
    if (proto === null) {
  21.  
    obj.__proto__ = null
  22.  
    }
  23.  
    return obj
  24.  
    }
学新通

14. 数组去重

ES5实现:

  1.  
    function unique(arr) {
  2.  
    var res = arr.filter(function(item, index, array) {
  3.  
    return array.indexOf(item) === index
  4.  
    })
  5.  
    return res
  6.  
    }

ES6实现:

var unique = arr => [...new Set(arr)]

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhghfhkc
系列文章
更多 icon
同类精品
更多 icon
继续加载