JavaScript基础:new 操作符

90 阅读1分钟

定义

new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。----MDN

例子
function Person(name, age) {
	this.name = name;
	this.age = age;
}
console.dir(Person.prototype);
const person = new Person('Jam', 27);
console.dir(person.__proto__);
console.dir(person);

console的内容
由输出的内容可以看出来,person.__proto__Person.prototype是相等的,而且person具有来nameage属性。因此new操作符在执行时做了以下的事情:

  1. 创建了一个新对象
  2. 将构造函数的this绑定到新对象
  3. 执行构造函数的代码
  4. 返回新对象
代码实现 new 过程
function mockNew(constructor) {
	const _that = {};
	_that.__proto__ = constructor.prototype;
	const args = Array.prototype.slice.call(arguments, 1);
	constructor.apply(that, args);
	return _that;
}
注意点

返回this的前提条件是该构造函数没有返回对象,则返回this。

function Person(name, age) {
	this.name = name;
	this.age = age;
	return {
		name: 'Jade',
		age: 5
	}
}
console.dir(Person.prototype);
const person = new Person('Jam', 27);
console.dir(person.__proto__);
console.dir(person);

console的内容