We need to know that when a new object is new, the bottom layer does the following 4 things:
- A new object is generated, namely {}
- 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)
- 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)
- 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)