JavaScript深入之new的模拟实现
废话不多说,直接上代码:
function objectFactory() {
var obj = new Object(),
Constructor = [].shift.call(arguments);
obj.__proto__ = Constructor.prototype;
var ret = Constructor.apply(obj, arguments);
return typeof ret === 'object' ? ret : obj;
};
测试一下:
unction Person(name,age){
this.name = name
this.age = age
}
Person.prototype.drink = 'cool'
function factory(){
var obj = new Object()
Constructor = [].shift.call(arguments)
obj.__proto__ = Constructor.prototype
var ret = Constructor.apply(obj,arguments)
return typeof ret === 'object'?ret:obj
}
var person = factory(Person,'xiaohong',43)
console.log(person.name)
console.log(person.age)
结果: