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
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/15998513.html
未经授权禁止转载,违者必究!