怎样手写实现 new 命令的功能

实现new命令的功能, 首先需要知道new命令都做了些什么: 

第一步: 创建一个空对象, 作为实例对象的容器;

第二步: 将空对象的prototype指向构造函数的prototype;

第三步: 将空对象赋值给构造函数的this;

第四步: 执行构造函数中的其它代码;

基于上面的步骤, 就有了下面这个手写的new命令的功能函数: 

function _new(/* 构造函数 */ constructor, /* 构造函数参数 */ params) {
  // 将 arguments 对象转为数组
  var args = [].slice.call(arguments);
  // 取出构造函数
  var constructor = args.shift();
  // 创建一个空对象,继承构造函数的 prototype 属性
  var context = Object.create(constructor.prototype);
  // 执行构造函数
  var result = constructor.apply(context, args);
  // 如果返回结果是对象,就直接返回,否则返回 context 对象
  return (typeof result === 'object' && result != null) ? result : context;
}

// 实例
var actor = _new(Person, '张三', 28);

猜你喜欢

转载自www.cnblogs.com/aisowe/p/11653595.html