I am attempting to build a small JavaScript library (similar to jQuery)
The purpose behind this is mostly a learning exercise, so asking why I don't just use an existing library is moot.
So far I have just got my basic constructor, a 'caller' function to invoke a new object, and some basic functions for an example.
var lemon = function() {
var prop = {
collection: []
};
var fn = {
init: function(selector, context) {
context = context || document;
if (!selector) {
return;
} else if (typeof selector == "string") {
prop.collection = fn.toArray(context.querySelectorAll(selector));
} else if (selector instanceof Array || selector instanceof NodeList) {
fn.toArray(selector).forEach(function(obj) {
prop.collection.push(obj);
});
} else if (selector instanceof Element) {
prop.collection.push(selector);
}
prop.length = prop.collection.length;
fn.extend.apply(this, [this, prop, fn]);
},
toArray: function(target) {
var array = [];
for (var i = target.length >>> 0; i--;) {
array[i] = target[i];
}
return array;
},
extend: function(target) {
var objects = Array.prototype.slice.call(arguments, 1);
objects.forEach(function(obj) {
var props = Object.getOwnPropertyNames(obj);
props.forEach(function(key) {
target[key] = obj[key];
});
});
return target;
},
addClass: function(klass) {
for (var i = 0, l = this.length; i < l; i++) {
this.collection[i].className += " " + klass;
}
return this;
}
};
fn.init.apply(this, fn.toArray(arguments));
};
var $ = function(selector, context) {
return new lemon(selector, context);
};