Skip to content

Instantly share code, notes, and snippets.

@chaozh
Created June 9, 2014 10:04
Show Gist options
  • Save chaozh/9692b4015b183560362e to your computer and use it in GitHub Desktop.
Save chaozh/9692b4015b183560362e to your computer and use it in GitHub Desktop.
for jquery learn
(function(exports, undefined){
//redefine document
var document = exports.document;
//namse space
var BASE = (function(){
// base obj
var BASE = function(selector, context){
return new BASE.fn.init();
}
BASE.fn = BASE.prototype = {
constructor: BASE,
};
//leave context to be null
init = BASE.fn.init = function(selector, context){
var match, elem;
var elems;
//handle $('')
if(!selector) return this;
else if(typeof selector == 'string'){
selector = selector.trim();
quickExpr = /^[\w-]*$/;
var mayID = selector[0] == '#',
mayClass = !mayID && selector[0] == '.',
nameOnly = mayID || mayClass ? selector.slice(1) : selector,
isSimple = quickExpr.test(nameOnly);
if(isSimple){
//handle $('#ID')
if(mayID){
elem = document.getElementById(nameOnly);
if(elem && elem.parentNode){
this.length = 1;
//use index 0 to store dom obj
this[0] = elem;
}
this.context = document;
return this;
}else if(mayClass){
//handle $('.CLASS') no context
if(document.getElementsByClassName){
elems = document.getElementsByClassName(nameOnly);
}
this[0] = elems;
return this;
}else{
elems = document.getElementsByTagName(nameOnly);
}
}else{
//try complex selector
elems = document.querySelectorAll(selector);
}
}
};
init.prototype = BASE.fn;
return BASE;
})();
//may confilct?
//exports.BASE = exports.$ = BASE;
exports.BASE = BASE;
exports.$ === undefined && (exports.$ = BASE);
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment