// 原生js实现
function _new() { const { constructor, arg } = arguments[0]; if (typeof constructor !== 'function') { throw 'first param must be function' } let target = {}; target.__proto__ = constructor.prototype; let result = constructor.apply(target, [arg]); if (result && (typeof result === 'object' || typeof result === 'function')) { // 如果构造函数返回一个对象,那就返回这个对象 return result } return target }
// 借助es6实现
function _new(){ const { constructor, arg } = arguments[0]; if(typeof constructor !== 'function'){ throw 'newOperator function the first param must be a function'; } // es6中为target指向constructor _new.target = constructor; // es6实现 var newObj = Object.create(constructor.prototype); var result = constructor.apply(newObj, [arg]); if (result && (typeof result === 'object' || typeof result === 'function')) { // 如果构造函数返回一个对象,那就返回这个对象 return result } return newObj; }
// 验证
function A(b) {this.b = b} A.prototype.c = function(){console.log('this.b',this.b)} let a = _new({ constructor: A, arg: 'b' }) a.c()