new的原理以及底层实现

2,543 阅读1分钟


new

一句话介绍 new:

new 运算符创建一个对象实例或具有内置构造函数

new一般多用于创建对象时使用,如下

function Person(name,age){
    this.name=name
    this.age=age 
    this.sayHi=function(){ console.log('hi') }
}
var p=new Person('xiaoMing',21)
console.log(p)
//输出结果
p={ 
name:'xiaoMing',
age:21,
sayHi:function(){console.log('hi')
}

上面那个简单例子看完后你可能会觉得,不就是创建个实例嘛。接下来带大家了解下new的过程

new的过程发生了什么?

  1. 创建一个空对象,构造函数中的this指向这个空对象
  2. 这个新对象被执行 [[原型]] 连接
  3. 执行构造函数方法,属性和方法被添加到this引用的对象中
  4. 如果构造函数中没有返回其它对象,那么返回this,即创建的这个的新对象,否则,返回构造函数中返回的对象。

function _new(){
	let target={}
	let[constructor,...args]=[...arguments] //通过参数绑定构造函数和参数
	target.__proto__=constructor.prototype //新对象和构造函数使用原型链连接
	constructor.apply(target,args) //执行构造函数,通过apply传入this和参数
	return target 
}

完。