new操作符的执行过程
- 首先创建了一个新的空对象;
- 我们将传入的参数对象arguments利用Array.from()转化为数组。
- 利用shift()弹出数组的第一个元素,也就是传入的构造函数,并保存到了变量constructor里。
- 设置原型;将空对象的隐式原型设置为构造函数的 prototype 对象。
- 让函数的 this 指向这个新创建的空对象,并调用函数得到返回值。
- 判断返回值类型,如果是基本数据类型,则返回我们创建的对象。如果是引用类型,就返回这个引用类型的对象。
function _new() {
// 创建了一个空对象
let obj = null
// 将伪数组转为真数组
let arr = Array.from(arguments)
// 得到第一个参数:构造函数(Person)
let constructor = arr.shift()
// 将obj的原型设置为constructor的prototype对象,并添加say1方法
obj = Object.create(constructor.prototype,{
say1:{
value: function(){
console.log('>>> say1 执行了')
}
}
})
// 将constructor的this指向newObj,并执行函数,拿到返回值
let result = constructor.call(obj, ...arr)
// 判断返回值类型
if (result instanceof Object) {
// 如果不是基本数据类型,则返回该函数的返回值
return result
} else {
// 是基本数据类型,则返回该obj
return obj
}
}
function Person(nam,age) {
this.nam = nam
this.age = age
}
Person.prototype.say = function(){
console.log(`${this.nam}--${this.age}`)
}
var test = _new(Person, 'Tom',13)
console.log('test:',test) // test: Person {nam: 'Tom', age: 13, say1: ƒ}
test.say() // Tom--13
test.say1() // >>> say1 执行了
网友评论