Implement the JS new operator

One, about the new operator

This blog mainly focuses on how to implement the new operator. Those who don’t know new can take a look at this blog.
Link: Talk about what the JS new operator does

2. Preliminary preparation: What needs to be done to implement a new operator

  1. Create an empty object instance
  2. Bind the this of the constructor to point to instance, and execute the constructor to set attributes for instance
  3. Point the prototype chain of the instance to the prototype of the constructor
  4. If the constructor specifies the return value ret of the reference type, then return ret, otherwise, since the return instance is

    ready, let’s start the code~

Third, implement the JavaScript new operator

code show as below

function _new(ctor) {
    
    
    if (typeof ctor !== 'function') {
    
    
        throw 'first parameter must be a function !'
    }
    // 创建实例,链接原型
    var instance = Object.create(ctor.prototype)
    // 提取形参列表
    var params = Array.prototype.slice.call(arguments, 1)
    // 绑定this,设置属性,获取构造函数的返回值
    var customReturn = ctor.call(instance, ...params)
    // 如果构造函数自身有引用类型的返回值,那么返回自身,否则返回instance
    var isCustomReturnAvailable = typeof customReturn === 'object' || typeof customReturn === 'function'
    // ES6 new.target一般在函数体中使用,在构造函数中返回函数的引用,在普通函数中返回undefined
    _new.target = ctor
    return isCustomReturnAvailable ? customReturn : instance
}

Test case

function Apple(size) {
    
    
    this.size = size
}
function CustomApple() {
    
    
    return {
    
    
        size: 'big'
    }
}
Apple.prototype.color = 'red'
console.log(_new(Apple, 'huge')) // Apple { size: 'huge' }
console.log(new Apple('huge')) // Apple { size: 'huge' }
console.log(_new(CustomApple, 'huge')) // { size: 'big' } 

result
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41109610/article/details/113480453