试着实现JS源码(持更...

本文详细解析并实践了JavaScript中的new操作符的工作原理,以及如何手动实现浅拷贝、深拷贝、Array.isArray和instanceof。通过理解这些基础概念,有助于提升JavaScript编程技能。
1. 实现 new

先看看平时我们是怎么使用new的:

function Person(name, age){
    this.name = name;
    this.age = age;
}
let person = new Person('zs', 20);

在以上代码中,new实际做了以下几件事:

  1. 创建一个新对象
  2. 改变构造函数中的作用域指向:this指向新对象
  3. 将构造函数接收的参数,为对象中的属性赋值
  4. 返回这个对象

分析完,我们就可以动手实现了:

function myNew(Constructor){
    return function(){
        let obj = new Object();
        obj.__proto__ = Constructor.prototype;
        Constructor.call(obj, ...arguments);
        // Constructor.apply(obj, arguments);
        return obj;
    }
}

function Person(name, age){
    this.name = name || 'zs';
    this.age = age || 20;
}

let person1 = myNew(Person)('ls', 18);
let person2 = myNew(Person)();
2. 实现浅拷贝
let obj = {a: 1, b: {c: 2}};

// 1. ...运算符
let newObj = {...obj};

// 2. Object.assign
let newObj = Object.assign({}, obj);

// 3. 自定义simpleCopy函数
function simpleCopy(obj){
    let newObj = obj instanceof Array ? [] : {};
    // let newObj = Array.isArray(obj) ? [] : {};
    // let newObj = obj.constructor.name === "Array" ? [] : {};
    for(let i in obj){
        newObj[i] = obj[i];
    }
    return newObj;
}
3. 实现深拷贝
// 1. 自定义deepCopy函数
function deepCopy(obj) {
  let newObj = Array.isArray(obj) ? [] : {};
  for(let i in obj){
    if(obj.hasOwnProperty(i)){
      if(obj[i] && typeof obj[i] === "object"){
        newObj[i] = deepCopy(obj[i]);
      }else{
        newObj[i] = obj[i];
      }
    }
  }
  return newObj;
}

// 2. JSON.stringify JSON.parse
let newObj = JSON.parse(JSON.stringify(obj));
4. 实现 Array.isArray
Array.myIsArray = function(obj){
    return obj.constructor.name === 'Array';
    // return Object.prototype.toString.call(obj) === '[object Array]';
}
5. 实现 instanceof

利用while循环,向上查询实例对象的原型链,判断实例对象的原型对象是否等于传入的构造函数的原型对象,直至实例对象的原型为null,返回false

function myInstanceof(obj, constructor){
    let protoObj = constructor.prototype;
    obj = obj.__proto__;
    while(true){
        if(obj == null) return false;
        if(obj === protoObj) return true;
        obj = obj.__proto__;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值