js new keyword under the hood All In One


js new keyword under the hood All In One

js new 实现原理剖析

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

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 函数



refs

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

https://twitter.com/venkat_s


Flag Counter

?xgqfrms 2012-2020

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

原创文章,版权所有??xgqfrms, 禁止转载 ???,侵权必究??!