function$(){
var elements = [];
for(vari=0,len=arguments.length;i<len;++i){
var element = arguments[i];
if(typeof element ===”string”){
element = document.getElementById(element);
}
if(arguments.length==1){
return element;
}
elements.push(element);
}
elements;
}
((){
//use private class
_$(els){
this.elements = [];
){
els[i];
”string”){
element = document.getElementById(element);
}
this.elements.push(element)
}
}
The public interface remains the same.
window.$ = (){
return new _$(arguments);
}
})();
(use private class
..省略之前上面的代码
}
_$.prototype = {
each:(fn){
for(var i=0,len=this.elements.length;i<len;i++){
fn.call(this,.elements[i]);
}
;
},show:(prop,val){
var that = ;
this.each((el){
that.setStyle("display”,”block");
});
(type,fn){
var add = (el){
if(window.addEventListener){
el.addEventListener(type,fn,false);
}else (window.attachEvent){
el.attachEvent("on"+type,fn);
}
};
(el){
add(el);
});
;
}
};
window.$ = (){
_$(arguments);
}
})();
window.installHelper = (scope,interface) {
scope[interface] = () {
_$(arguments);
}
};
installHelper(window,'$');
$('example').show();
Define a namespace without overwriting it if it already exists.
window.com = window.com || {};
com.example = com.example || {};
com.example.util = com.example.util || {};
installHelper(com.example.util,'get');
(function() {
var get = com.example.util.get;
get(example').addEvent(click,function(e) {
get(this).addClass(hello);
});
})();
Accessor without function callbacks: returning requested data in accessors.
window.API = window.API || {};
API.prototype = () {
var name = 'Hello world' Privileged mutator method.
setName: (newName) {
name = newName;
;
},1)"> Privileged accessor method.
getName: () {
name;
}
}();
Implementation code.
var o = API;
console.log(o.getName()); Displays 'Hello world'.
console.log(o.setName('Meow').getName()); Displays 'Meow'.
Accessor with function callbacks.
window.API2 = window.API2 || {};
API2.prototype = Privileged accessor method.
通过把函数作为参数传入
getName: (callback) {
callback.call(;
}
}();
var o2 = API2;
o2.getName(console.log).setName('Meow').getName(console.log);
Displays 'Hello world' and then 'Meow'.