javascript中的new 操作符

new操作符干了四件事

1.新建了一个空对象

2.更新原型链  把实例的_proto_指向构造函数的prototype

3.修改构造函数中的this环境,把this指向新的实例

4.检查函数返回值,如果该函数会返回一个新的对象,那么更新为返回值(会失去原型链),而不是被带入的this实例环境  【注:仅限对象,其他类型不会改变结果】

	        function Base(){
		         this.id = '123'
				     return {
					 text: "text"
				 }
			 }
			 var b = new Base()
			 console.log(b) // {text:"text"}
			 console.log(b.id) // undefined
			 
			var ba = {}; // 新建一个空对象
			ba.__proto__ = Base.prototype;  // _proto_ = prototype  更新原型链
			var rl = Base.call(ba)  //  更改this指向 指向构造函数 并存储结果
			if (rl instanceof Object) { //  如果返回一个对象,则实例为该对象,否则不变
			    ba = rl
			}
			console.log(ba) // {text:"text"}
			console.log(ba.id) // undefined  

猜你喜欢

转载自blog.csdn.net/wanghongpu9305/article/details/114023255