new func()
主要过程以下:bash
obj
;obj.__proto__ = func.prototype
;func.call(obj)
;return obj
。对于第三、4步还有个小细节,若是第3步func
有返回值且返回值为对象,则第4步会返回func
的返回值,反之则默认返回obj
。函数
模仿new原理的代码以下:ui
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(),它的做用是以入参为原型建立一个空对象,即this
Object.create = function (obj) {
return { '__proto__': obj};
};
复制代码
或spa
Object.create = function (obj) {
function F() {}
F.prototype = obj;
return new F();
};
复制代码