//new运算符的伪码实现
function _new(clazz, args){
//clone(clazz.prototype)
var _this = {};
_this.__proto__ = clazz.prototype;
var obj = clazz.apply(_this, args);
var type = typeof obj;
if(type == "object" && obj !== null || type == "function"){
return obj;
}else{
return _this;
}
/* 另一种写法
if(obj === null || type == "undefined" || type == "boolean"
|| type == "number" || type == "string"){
return _this;
}else{
return obj;
}
*/
}
var a = new ClassA(1,2);
var a = _new(ClassA, [1,2]); //伪码
JS模拟的new运算符工作原理(new运算符的伪码实现)
最新推荐文章于 2023-06-03 15:00:12 发布