/**
* new 做了什么?
* 1. 创建一个空对象
* 2. 设置原型链
* 3. 绑定this
* 4. 返回对象
*/
// 例子
function _new(F, ...args) {
// 创建一个空对象
const obj = Object.create(null)
// 设置原型链指向函数原型
Object.setPrototypeOf(obj, F.prototype)
// obj.__proto__ = F.prototype
// 绑定this
F.apply(obj, args)
// 返回对象
return obj
}
// 测试
function A() {
this.name = 'A'
Array.from(arguments).forEach(item => {
this[item] = item
})
}
const a = _new(A, 1, 2)
const a1 = _new(A)
console.log(a);
console.log(a1);
JavaScript的new关键字做了什么?
最新推荐文章于 2024-07-26 11:41:15 发布