'Best way to implement a library
I have created a library, for the sake of learning, with a few methods in the Global Object, Global Function Object, and the Global Array Object, apart from my own Object created inside the library.
I've created the library inside an IIFE and then passed the arguments.
The methods are simulating basically other built-in methods but with my own logic just for learning purposes
The library with a few examples is the following.
(function (global, globalObj, globalArr, globalFunc) {
globalArr.prototype.forEach1 = function (fun) {
self = this;
for (let value of self) {
fun(value);
}
};
globalFunc.prototype.bind2 = function(context, ...a) {
return (...b) => this.call(context, ...a, ...b);
};
globalFunc.prototype.call2 = function(context, ...a) {
if (typeof context === "object") {
let bound = Symbol();
context[bound] = this;
console.log(this);
let result = context[bound](...a);
delete context[bound];
return result;
};
return this(...a);
};
myL.keys1 = function(obj) {
let keys = [];
for (let key in obj) {
if (obj.propertyIsEnumerable(key)) {
keys.push(key);
}
}
return keys;
};
myL.values1 = function(obj) {
let values = [];
let keys = myL.keys1(obj);
for (let key of keys) {
values.push1(obj[key]);
}
return values;
};
myL.instanceOf1 = function(obj, target) {
return obj.constructor == target.prototype.constructor;
};
myL.about = function(obj) {
let keys = M$.keys1(obj);
let values = M$.values1(obj);
let prot = obj.__proto__;
let constr = obj.constructor;
for (i=0; i < keys.length; i++) {
console.log(`Property ${i+1} and value:\n${keys[i]}: ${values[i]}.`);
};
console.log(`Object prototype is: ${prot}.`)
console.log(`Object constructor is: ${constr}.`)
};
global.myL = global.M$ = myL;
}(window, Object, Array, Function));
As you can see I have created a method for Array.prototype, Function.prototype, Object.prototype, and myL (my library).
Is this way the best one to create a library so anyone could use it outside?
I have tried it and I could actually use all the methods created and I had no interference with the variables and methods, but I am probably missing lots of things here.
Thank you !!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
