阶段二:js

90 阅读1分钟

一:js函数的三个方法的使用,可以改变函数中的this指向:call apply bind

函数.call(调用函数时内部this具有值-也就是调用的函数, 参数1,参数2)

函数.apply(调用函数时内部this具有值-也就是调用的函数, [参数1,参数2])

函数.bind(调用函数时内部this具有值-也就是调用的函数, 参数1,参数2)()

image.png

扩展:求数组的最大值可以使用apply Math.max.apply(null,[1,2,3,4])

二:new 具体做了什么事?

image.png

三:浅拷贝 Object.assign()

image.png

image.png

四:深拷贝:

image.png 方法一: image.png

方法二:递归

    // 原对象
    const oldObj = {
        name: "张三",
        age: 20,
        colors: ['orange', 'green', 'blue'],
        friend: {
            name: '小明'
        }
    }

    // 新对象
    // 浅拷贝 将新对象和 原对象都修改了
    // const newObj = oldObj
    // newObj.name = "lisi"
    // console.log(newObj); // {name: "lisi"}
    // console.log(oldObj); // {name: "lisi"}

    // 深拷贝
    // 定义一个函数
    function deepClone(obj = {}) {
        // 判断要拷贝的数据类型 是不是对象 ,如果是对象 直接返回
        if (typeof obj !== "object" || obj == null) {
            return obj
        }

        let result;
        // 判断 要拷贝的数据是否为数组 如果是数组 默认等于一个空数组
        if (obj instanceof Array) {
            result = [];
        } else {
            result = {}
        }

        // for in 循环拷贝的对象
        for (let key in obj) {
            result[key] = deepClone(obj[key] )  // result[name] = obj[name]  ==> result = {name: '张三'} 这里在调用一次这个方法就是递归
            
        }
        return result;
    }

    const newObj = deepClone(oldObj)
    newObj.name = "lisi"
    newObj.friend.name = 80
    newObj.colors[0] = 80

    console.log(oldObj,"oldObj 原始值"); 
    console.log(newObj,"newObj 新的值"); 
    

image.png