js basic review to implement a new method by yourself

We need to know that when a new object is new, the bottom layer does the following 4 things:

  1. A new object is generated, namely {}
  2. Link to the prototype (the popular understanding is that the implicit prototype of the new object __proto__ is linked to the explicit prototype prototype of the constructor)
  3. Bind this, and use the newly created object in step 1 as the context of this (actually the constructor is executed and the scope of the constructor points to the new object)
  4. Return new object
function _new(constructor, ...arg) {
    
    
	var obj = {
    
    }
	obj.__proto__ = constructor.prototype
	var result = constructor.apply(obj, arg) // 这一步绑定constructor内部的this到obj上,并且执行constructor构造函数
	return Object.prototype.toString.call(result) === '[object Object]' ? result : obj
}
// 测试
const myFunc = function(name) {
    
    
    this.name = name
}

var res = _new(myFunc, 'DeanWade')
console.log(res)

Insert picture description here

Guess you like

Origin blog.csdn.net/dyw3390199/article/details/112732171