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

js new keyword under the hood All In One

js new keyword under the hood All In One

js new 实现原理剖析

js custom new keyword

// 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;
}

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

multi arguments & dynamic arguments ✅

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

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

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



demo

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

const BMW = new Car('BMW', 2012);
BMW.getName();
BMW.getYear();


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

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

如何用 js 实现一个 new 函数



https://www.cnblogs.com/xgqfrms/p/13717265.html

refs

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

https://twitter.com/venkat_s



©xgqfrms 2012-2020

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

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


posted @ 2022-03-12 21:31  xgqfrms  阅读(53)  评论(6编辑  收藏  举报