new运算符

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 创建对象会进行哪些操作

  1. 首先会创建一个空对象,即 {}
  2. 为创建的对象添加__proto__ 属性,即隐式原型,将该属性指向构造函数的原型 。由这一点可以
  3. 将新创建的对象作为 this 的上下文;
  4. 如果构造函数没有返回对象,则返回 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值