es5 实现 new
by Alex Liu
JavaScript
function newOperator(ctor){
if(typeof ctor !== 'function'){
throw "must be a function"
}
var newObj = Object.create(ctor.prototype)
const args = Array.prototype.slice.call(arguments, 1)
const ret = ctor.apply(newObj, args)
if(typeof ret === 'object' && ret!==null || typeof ret === 'function'){
return ret
}
return newObj
}
function Student(name, age){
this.name = name
this.age = age
}
Student.prototype.getAge = function(){
return this.age
}
Student.prototype.getName = function(){
return this.name
}
const std = newOperator(Student, 'xiaoming', 12)
console.log(std instanceof Student)
console.log(Object.getPrototypeOf(std) === Student.prototype)