如何用 js 实现一个 ES6 class 类函数 All In One
如何用 js 实现一个 ES6 class 类函数 All In One
js class 原理
- 支持使用 new 创建类实例
- 包含 constructor 初始化
- 支持 static 静态方法
- 支持 extends 类继承
// private / public /protected ...
function CustomClass () {
console.log('arguments =', arguments);
// Array.prototype.slice.call
// const args = Array.prototype.slice.call(arguments, '');
// const args = Array.prototype.slice.call(arguments, 0);
const args = Array.prototype.slice.call(arguments);
console.log('args =', args);
this.args = args;
}
// CustomClass(1, 'a');
// arguments = Arguments(2) [1, 'a', callee: ƒ, Symbol(Symbol.iterator): ƒ]
// args = (2) [1, 'a']
// const test = new CustomClass(1, 'a');
// test.args;
Array.prototype.slice
const animals = ['ant', 'bison', 'camel'];
console.log(animals.slice());
console.log(animals.slice(''));
console.log(animals.slice(0));
// ['ant', 'bison', 'camel']
// ['ant', 'bison', 'camel']
// ['ant', 'bison', 'camel']
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
CustomClass.prototype.contructor = function () {
//
}
CustomClass.static = function () {
// 依赖收集
}
// getter / setter
实现方式
- new 使用 ES5 构造函数
// js custom new keyword
// 1. create an 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://www.cnblogs.com/xgqfrms/p/15998513.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
总结
refs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13849502.html
未经授权禁止转载,违者必究!