js中new的作用

1.在堆中开辟对象内存空间, 记为obj
2.在obj 中添加__proto__属性并指向 构造函数.prototype
3.将构造函数中的this 指向obj
4.执行构造函数内语句
5.若构造函数中没有reutrn 或return this或基本类型(number、string、boolean、null、undefined)的值,则返回obj在堆中的内存地址;若return 引用类型,则返回值为这个引用类型

仿写new

function People(name, age, phone) {
  this.name = name;
  this.age = age;
  this.phone = phone;
  //若构造函数中`没有reutrn 或return this或基本类型`(number、string、boolean、null、undefined)的值,则返回obj在堆中的内存地址;若`return 引用类型`,则返回值为这个引用类型
  // return null;//无影响
  // return {};//返回此对象
  // return function(){};//返回此函数
}

function _new(...args) {
  let constructor = args[0];//获取构造函数
  let obj = Object.create(constructor.prototype);//创建空对象,并将原型指向构造函数的原型
  let res = constructor.call(obj, ...args.slice(1));//call强行将this指向第一个参数
  if ((typeof res === 'object' || typeof res === 'function') && res != null) {
    return res;
  } else {
    return obj;
  }
}

let a = _new(People, 'aa', 20, 132456);
let na = new People('aa', 20, 132456);
console.log(a, na);
//运行结果
People { name: 'aa', age: 20, phone: 132456 }
People { name: 'aa', age: 20, phone: 132456 }

//console.log()在控制台输出引用值时确实是当时的值,但是你点开箭头的时候它会重新获取这些引用的值。

结构赋值自定义变量

var obj = {
  a:'123',
  b:123
}
var {a:mya,b} = obj;
console.log(mya,b) //'123',123
debounce(fn, wait) {
      let timeout = null;
      return function () {
        if (timeout !== null) clearTimeout(timeout);
        timeout = setTimeout(fn, wait);
      };
    }
    ```
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值