new
运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。
语法:
new constructor[([arguments])]
constructor
一个指定对象实例的类型的类或函数。
arguments
一个用于被 constructor 调用的参数列表。
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const car1 = new Car('Eagle', 'Talon TSi', 1993);
console.log(car1.make);
// Expected output: "Eagle"
那么使用new 创建对象会进行哪些操作
- 首先会创建一个空对象,即 {}
- 为创建的对象添加__proto__ 属性,即隐式原型,将该属性指向构造函数的原型 。由这一点可以
- 将新创建的对象作为
this
的上下文; - 如果构造函数没有返回对象,则返回
this
。
// 对于第四点
function User1(){
this.name = "张三"
this.toString = function(){return this.name};
return {
name:"李四"
}
}
const user1 = new User1();// 等同于这种写法 const user1 = new User 不传参数
// 由于该构造函数返回了一个对象 ,因此将该对象赋值给变量
console.log(user1.name); // 李四
console.log(user1.toString()) // [Object object] 由于实例上没有toString方法 因此调用原型上的toString方法
// 对于第二点 改变对象的原型链
function Car(brand){
this.brand = brand;
}
Car.prototype.info=function(){return "汽车:"+this.brand};
function Cat(brand){
this.brand = brand;
}
Cat.prototype.info=function(){return "猫:"+this.brand};
Car.prototype = Cat.prototype
const car = new Car("大牛");
console.log(car.info()); // 猫:大牛
console.log(car.__porto__ === Car.prototype) // false
console.log(car.__proto__ === Cat.prototype) // true