new func()
主要過程以下:函數
obj
;obj.__proto__ = func.prototype
;func.call(obj)
;return obj
。對於第三、4步還有個小細節,若是第3步func
有返回值且返回值爲對象,則第4步會返回func
的返回值,反之則默認返回obj
。this
模仿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; } };
在模仿new原理的代碼中用到了Object.create(),它的做用是以入參爲原型建立一個空對象,即code
Object.create = function (obj) { return { '__proto__': obj}; };
或對象
Object.create = function (obj) { function F() {} F.prototype = obj; return new F(); };