JavaScript中new操做符和Object.create()的原理

new

new func()主要过程以下:函数

  1. 建立一个空对象obj
  2. 将该空对象的原型设置为构造函数的原型,即obj.__proto__ = func.prototype
  3. 以该对象为上下文执行构造函数,即func.call(obj)
  4. 返回该对象,即return obj

对于第三、4步还有个小细节,若是第3步func有返回值且返回值为对象,则第4步会返回func的返回值,反之则默认返回objthis

模仿new原理的代码以下:prototype

function new2(func) { // func为某个构造函数
  var createObject = Object.create(func.prototype); // 以构造函数的原型对象为原型,建立一个空对象,即建立一个{ __proto__: func.prototype }
  var returnObject = func.call(createObject); // 使用刚建立的空对象做为上下文(this)执行构造函数
  if (typeof returnObject === 'object') { // 若构造函数有返回对象,则返回该对象
    return returnObject;
  } else { // 若构造函数未返回对象,则返回Object.create建立的对象
    return createObject;
  }
};

Object.create()

在模仿new原理的代码中用到了Object.create(),它的做用是以入参为原型建立一个空对象,即code

Object.create = function (obj) {
  return { '__proto__': obj};
};

对象

Object.create = function (obj) {
  function F() {}
  F.prototype = obj;
  return new F();
};
相关文章
相关标签/搜索