(前端)new操作符的执行过程是什么

2023-11-30  本文已影响0人  码农私房菜

new操作符的执行过程

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 执行了
上一篇 下一篇

猜你喜欢

热点阅读