function myNew(){
var constructor = Array.prototype.shift.call(arguments), //获取第一个参数
result = null, //存结果
newObj = null, //存放新对象
flag = false; //判断返回值是不是对象或函数flag
if(!constructor || typeof constructor !== 'function'){//判断参数
throw new Error('类型错误!')
}
newObj = Object.create(constructor.prototype); //创建新空对象,对象原型为构造函数的 prototype 对象
result = constructor.apply(newObj, arguments); //this 指向新建的对象,并执行函数
flag = result && typeof result === 'object' || typeof result === 'function' ? true : false; //判断返回值类型
return flag ? result : newObj; //如果是值类型,返回创建的对象。如果是引用类型,就返回这个引用类型的对象
}
使用方法
function example(name){
this.name = name;
this.sayName = function(){
console.log(this.name)
}
}
var myExample = myNew(example, 'effie');
运行结果如下: