xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

如何使用 js 实现一个 new 函数 All In One

如何使用 js 实现一个 new 函数 All In One

原理

new 关键字实现经过了如下过程

  1. 创建一个空对象 obj = {}
  2. 链接到原型 obj.proto = constructor.prototype
  3. 绑定 this 值 constructor.call(obj)
  4. 返回一个新对象

实现方式

// 1. create object, allocate memory

// 2. bind this

// 3. bind prototype

// 4. return object

function CustomNew (Func, args) {
   // const obj = Object.create(func);
   const obj = {};
   // const obj = Object.assign({});
   Func.call(obj, args);
   // Func.call(obj, ...args);
   // Func.apply(obj, [...args]);
   obj.__proto__ = Func.prototype;
   return obj;
}


demos

function Car (name) {
  this.name = name;
  this.getName = function () {
    console.log('car name =', this.name);
  }
}

const BMW = new Car('BMW');
BMW.getName();

const Tesla = CustomNew(Car, 'Tesla');
Tesla.getName();

总结

js new (under the hood)

https://youtu.be/ZUHyZHwZtUY?t=2420


demos

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/new



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2020-09-23 11:45  xgqfrms  阅读(512)  评论(3编辑  收藏  举报