前端面试自测知识点---new和手写new

new
new 操作一个构造函数或类来获取实例
// ES5中的构造函数
function Person(name, age){
  this.name = name;
  this.age = age
}

Person.prototype.sayAge = function(){
  console.log(`${this.name} is ${this.age} years old`)
}

var lucy = new Person("Lucy", 18)
lucy.sayAge() // Lucy is 18 years old

// ES6中的class
class Person{
  constructor(name,age){
    this.name = name;
    this.age = age
  }
  sayAge(){
    console.log(`${this.name} is ${this.age} years old`)
  }
}
var lucy = new Person("Lucy", 18) // Lucy is 18 years old
lucy.sayAge()
new操作中做了什么
  • 以构造器的prototype为原型,创建新对象;

  • 将this(也就是上一步创建出的新对象)和调用参数传给构造器,执行;

  • 如果构造器没有手动返回对象,则返回第一步创建的新对象,如果有,则舍弃掉第一步创建的新对象,返回手动return的对象

    new过程中会新建对象,此对象会继承构造器的原型与原型上的属性,最后它会被作为实例返回这样一个过程

手写一个new方法
let newMethod = function(Parent, ...rest){
  // 1、以构造器的prototype属性为原型,创建新对象
  let child = Object.create(Parent.prototype)
  // 2、将this(也就是上一句中的新对象)和调用参数传给构造器,执行
  let result = Parent.call(child, ...rest)
  // 3、如果构造器没有手动返回对象,则返回第一步创建的新对象,如果有,则舍弃掉第一步创建的新对象,返回手动return的对象
  return result instanceof Object ? result : child
}

let Parent = function (name, age) {
  this.name = name;
  this.age = age;
};

测试使用

let Parent = function (name, age) {
  this.name = name;
  this.age = age;
};
Parent.prototype.sayName = function () {
  console.log(this.name);
};

const child = newMethod(Parent, 'Kitty', 100);
child.sayName() // Kitty
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值