The new operator in javascript

The new operator does four things

1. Create a new empty object

2. Update the prototype chain to point the _proto_ of the instance to the prototype of the constructor

3. Modify the this environment in the constructor to point this to the new instance

4. Check the function return value. If the function returns a new object, then update to the return value (the prototype chain will be lost) instead of the this instance environment brought into it.   [Note: Only objects, other types will not change result】

	        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  

 

 

 

 

Guess you like

Origin blog.csdn.net/wanghongpu9305/article/details/114023255