首先new执行和普通函数执行的原理区别,
- 创建一个空对象
- 初始化this:让this指向创建的对象
- 代码执行中遇到this.xxx都是给创建的实例对象设置‘私有’的属性方法
- 如果没有return,默认把创建的对象返回,如果有return并且return的是引用数据类型,则把自己返回的返回。
根据上述的原理可以写出这样的new
// Func 创造实例的类 params 给类传递的实参
function _new(Func,...params){
let obj = {};
obj.__proto__ = Func.prototype;
let result = Func.call(obj,...params);
if(result!==null&&/^(object|function)$/i.test(typeof result)) return result;
return obj;
}
优化 _ _ proto _ _ IE不兼容
Object.create() 静态方法以一个现有对象作为原型,创建一个新对象。参数为新创建对象的原型对象。
function _new(Func, ...params) {
let obj = Object.create(Func.prototype);
let result = Func.call(obj, ...params);
if (result !== null && /^(object|function)$/i.test(typeof result)) return result;
return obj;
}
优化 Object.create是ES2015(不是ES5,是ES6前身)提供的方法,不兼容低版本浏览器,所以自己手写一个Object.create
Object.create = function create(obj) {
if (obj === null || typeof obj !== "object") {
throw new TypeError('Object prototype may only be an Object');
}
function Anonymous() {}
Anonymous.prototype = obj;
return new Anonymous;
};