js new之后发生了什么

39 阅读1分钟

1、自从用new调用函数后,JS引擎就会在内存中创建一个空对象{}

const newObj = {};

2、 新对象的__proto__属性指向构造函数的原型对象 (通俗理解就是新对象隐式原型__proto__链接到构造函数显式原型prototype上。)

newObj.__proto__ = functionName.prototype

3、构造函数内部的this会指向这个新对象(即将构造函数的作用域指向新对象)

this = newObj

4、返回创造出来的对象(如果构造函数没有返回对象,则默认返回this。在函数体内部的this指向新创建的内存空间,默认返回 this 就相当于默认返回了该内存空间)

return this

function Person(name, age) {
	this.name = name;
	this.age = age;
	this.eating = function() {
		console.log(this.name + ' is eating');
	}
}
const p1 = new Person('zs', 12);

//----------------------------------------------------------------------------
/*JS引擎帮助我们实现的操作*/

const newObj = {};
newObj.__proto__ = Person.prototype;
this = newObj;
return newObj;