function newObj(...args) {
// 第一个为构造函数
const constructor = args.shift()
//创建一个空对象obj,并让其继承Func.prototype
const obj = Object.create(constructor.prototype)
//执行构造函数,并将this指向创建的空对象obj
const result = constructor.apply(obj, args)
// 如果构造函数内部有return语句,而且return后面跟着一个对象,
// new命令会返回return语句指定的对象;否则,就会不管return语句,返回this对象。
// 判断构造函数返回的结构是对象就直接返回 如果不是就返回创建的obj
return (typeof result == 'object' && result !== null) ? result : obj
}
function Person(name) {
this.name = name
}
const xiaoyu = newObj(Person, 'xiaoyu')
console.log(xiaoyu)
js实现new功能
于 2023-10-28 12:53:35 首次发布