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();
};
相關文章
相關標籤/搜索