源码共读07:能否模拟实现JS的new操作符

128 阅读5分钟

本文参加了由公众号@若川视野 发起的每周源码共读活动, 点击了解详情一起参与。

这是面试官问系列第一篇,链接: juejin.cn/post/684490…

new 做了什么?

// 先看例子1
function Student() {}

var student = new Student();
console.log(student); // {}
// student 是一个对象
console.log(Object.prototype.toString.call(student)); // [object object]
// 平时声明对象也可以使用new Object();只是看起来比较复杂。
// 顺便提一下, `new Object`(不推荐)也可以和new Object()一样的效果。
// 可以猜测,内部做了一次判断,用new调用
/** 
* if (!(this instanceof Object)) {
*   return new Object();
* }
**/
var obj = new Object();
console.log(obj); // {}
console.log(Object.prototype.toString.call(obj)); // [object object]

typeof Student === 'function'; // true
typeof Object === 'function'; // true

从这个例子中,可以看出:一个函数用new操作符来调用后,生成一个全新的对象。而且Student和Object都是函数,只不过Student是我们自定义的,Object是js内置的。再看下控制台输出:

与new Object()不同的是new Student()生成的对象中间还嵌了一层__proto__,它的contructor是Student这个函数。

// 也就是说:
student.contructor === Student
student.prototype.contructor === Object

小结1:从这个简单例子来看,new操作符做了两件事:

  1. 创建了一个全新的对象
  2. 这个对象会被执行[[prototype]](也就是__proto__)链接。

接下来再看升级版例子2:

// 例子2
function Student(name) {
  console.log('赋值前-this', this); // {}
  this.name = name;
  console.log('赋值后-this', this); // {name: 'sam'}
}
var student = new Student('sam');
console.log(student); // {name: 'sam'}

由此可以看出,这里的Student函数中的this指向new Student()生成的对象student。

小结2:从这个例子来看,new又做了一件事:

  1. 生成的新对象会绑定到函数调用的this

接下来继续看升级版例子3:

// 例子3
function Student(name) {
  this.name = name;
  
}
Student.prototype.doSth = function() {
  console.log(this.name);
}
var student1 = new Student('sam');
var student2 = new Student('hoson');
console.log(student1, student1.doSth()); // {name: 'sam'} 'sam'
console.log(student2, student2.doSth()); // {name: 'hoson'} 'hoson'
student1.__proto__ === Student.prototype; // true
student2.__proto__ === Student.prototype; // true
// __proto__ 是浏览器实现的查看原型的方案
// 用ES5, 则是
Object.getPrototypeOf(student1) === Student.prototype; // true
Object.getPrototypeOf(student2) === Student.prototype; // true

JavaScriupt原型关系图

小结3:这个例子再次验证小结1的第二点。也就是这个对象会被执行[[Prototype]](也就是__proto__)链接。并且通过new Student()创建的每个对象将最终被[[prototype]]链接到这个Student.prototype对象上。

这三个例子都没有返回值。那么如果有返回值会是怎么样的情况呢?

例子4:

function Student(name) {
  this.name = name;
  // Null(空) null
  // Undefined(未定义)undefiend
  // Number(数字)1
  // String(字符串)'sam'
  // Boolean(布尔)true
  // Symbol (symbol) ES6新增 symbol
  
  // Object(对象){}
  // Function(函数)function() {}
  // Array(数组)[]
  // Date(日期)new Date()
  // RegExp(正则)/a/
  // Error(错误)new Error()
  return null
}

var student = new Student('sam');
console.log(student); // {name: 'sam'}

实际测试结果:前面六种基本类型都会正常返回{name: 'sam'};,后面的Object(包含Function、Array、Date、RegExp、Error);都会直接返回这些值。

小结4:

  1. 如果函数没有返回Object(包含Function、Array、Date、RegExp、Error),那么new表达式中函数调用都会自动返回这个新的对象。

结合这些小结,整理在一起就是:

  1. 创建了一个全新的对象
  2. 这个对象会被执行[[prototype]](也就是__proto__)链接。
  3. 生成的新对象会绑定到函数调用的this
  4. 通过new创建的每个对象将最终被[[Prototype]]链接到这个函数的prototype对象上。
  5. 如果函数没有返回对象类型Object(包含Function、Array、Date、RegExp、Error),那么new表达式中的函数调用会自动返回这个新的对象。

new 模拟实现

/**
* 模拟实现 new 操作符
* @param {Function} ctor [构造函数]
* @return {Object|Function|Regexp|Date|Error}
**/
function newOperator(ctor) {
  if (typrof ctor !== 'function') {
    throw 'newOpertor function the first param must be a function';
  }
  // ES6 new.target 是指向构造函数
  newOperator.target = ctor;
  // 1.创建一个对象
  // 2.并且执行[[prototype]]链接
  // 4.通过`new`创建的每个对象将最终`[[prototype]]`链接到这个函数的`prototype`对象上。
  var newObj = Object.create(ctor.prototype);
  // ES5 arguments转数组 当然也可以用ES6 [...arguments], Array.from(arguments);
  // 除去ctor构造函数的其余参数
  var argsArr = [].slice.call(arguments, 1);
  // 3.生成的新对象绑定到函数调用的`this`
  // 获取到ctor函数返回结果
  var ctorReturnResult = ctor.apply(newObj, argsArr);
  // 小结4 中这些类型中合并起来只有Object和Function两种类型 typeof null 也是 'object',所以不等于null,排除null
  var isObject = typeof ctorReturnResult === 'object' && typeof ctorReturnResult !== 'null';
  var isFunction = typeof ctorReturnResult === 'function';
  if (isObject || isFunction) {
    return ctorReturnResult;
  }
  // 5.如果函数没有返回对象类型`Object`(包含Function、Array、Date、Regexp、Error),那么new 会自动返回这个新对象
  return newObj;
}

最后模拟实现的newOperator函数验证下之前的例子3:

// 例子3 多加一个参数
function Student(name, age) {
  this.name = name;
  this.age = age;
  //return Error;
  // return 1;
}
Student.prototype.doSth = function() {
  console.log(this.name)
}
var student1 = newOperator(Student, 'sam', 1);
var student2 = newOperator(Student, 'hoson', 2);

console.log(student1, student1.doSth()); // { name: 'sam', age: 1}
console.log(student2, student2.doSth()); // { name: 'hoson', age: 2 }

student1.__proto__ === Student.prototype; // true
student2.__proto__ === Student.prototype; // true

Object.getPrototypeOf(student1) === Student.prototype; // true
Object.getPrototypeOf(student2) === Student.prototype; // true

Object.create()

Object.create(proto, [protertiesObject])方法创建一个新对象,使用一个现有对象来提供新创建的对象的__proto__。它接受两个参数,不过第二个可选参数是参数描述符(不常用,默认是undefined)。

var newObject = {
  name: 'sam'
}

var object1 = Object.create(newObject, {
  age: {
    value: 1
  }
})
// 获取它的原型
Object.getPrototypeOf(newObject) === Object.prototype
Obvject.getPrototypeOf(object1); // { name: 'sam' }
myObject.hasOwnPrototype(name); // true
myObject.hasOwnPrototype(age); // true
myObject.name; // 'sam'
myObject.age; // 1

对于不支持ES5的浏览器,MDN上提供了ployfill方案:

if (typeof Object.create !== 'function') {
  Object.create =function(proto, propertiesObject) {
    if (typeof proto !== 'function' || typeof propertiesObject !== 'function') {
      throw new TypeError()
    } else if (proto === null) {
      throw new Error()
    }
    
    if (typeof propertiesObject != 'undefined') throw new Error()
    
    function F() {};
    F.prototype = proto;
    return new F();
  } 
} 

总结

  1. 创建了一个空对象
  2. 将创建的对象被[[prototype]](也就是__proto__)链接
  3. 将创建的对象绑定到调用的函数的this
  4. 通过new 创建的每个对象将最终被[[prototype]]链接到这个函数的prototype对象上。
  5. 如果对象返回的不是Object(Function、Array、Undefined、Date、Regexp、Error),那么new表达式中函数调用会自动返回这个新的对象。
function newOperator(ctor) {
  if (typeof ctor !== 'function') {
    throw 'newOperator function the first param must be a function' ;
  }
  newOperator.target = ctor;
  
  var newObj = Object.create(ctor.prototype);
  var argsArr = [].slice.call(arguments, 1);
  var ctorReturnResult = ctor.apply(newObj, argsArr);
  var isObject = typeof ctorReturnResult === 'object' && ctorReturnResult !== null;
  var isFunction = typeof ctorReturnResult === 'function';
  if (isObject || isFunction) {
    return ctorReturnResult;
  }
  return newObj;
}

image.png

  1. f是一般函数
  2. 箭头表示原型关系

此文章为2024年02月Day2源码共读,每一次脑海里闪过努力的念头,都是未来的你在向你求救。