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

139 阅读1分钟

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__;
    }
}