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);
}
return elements;
}
|
(function(){
//use private class
function _$(els){
this.elements = [];
for(vari=0,len=els.length;i<len;i++){
var element = els[i];
if(typeof element ===”string”){
element = document.getElementById(element);
}
this.elements.push(element)
}
}
//The public interface remains the same.
window.$ = function(){
return new _$(arguments);
}
})();
|
_$这个私用构造函数的prototype对象中添加方法,以便实现链式调用
(function(){
//use private class
function _$(els){
//..省略之前上面的代码
}
_$.prototype = {
each:function(fn){
for(var i=0,len=this.elements.length;i<len;i++){
fn.call(this,this.elements[i]);
}
return this;
},
show:function(prop,val){
var that = this;
this.each(function(el){
that.setStyle("display”,”block");
});
return this;
},
addEvent:function(type,fn){
var add = function(el){
if(window.addEventListener){
el.addEventListener(type,fn,false);
}else if(window.attachEvent){
el.attachEvent("on"+type,fn);
}
};
this.each(function(el){
add(el);
});
return this;
}
};
//The public interface remains the same.
window.$ = function(){
return new _$(arguments);
}
})();
|
window.installHelper = function(scope, interface) {
scope[interface] = function() {
return new _$(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 = function() {
var name = 'Hello world';
// Privileged mutator method.
setName: function(newName) {
name = newName;
return this;
},
// Privileged accessor method.
getName: function() {
return name;
}
}();
// Implementation code.
var o = new 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 = function() {
var name = 'Hello world';
// Privileged mutator method.
setName: function(newName) {
name = newName;
return this;
},
// Privileged accessor method.
//通过把函数作为参数传入
getName: function(callback) {
callback.call(this, name);
return this;
}
}();
// Implementation code.
var o2 = new API2;
o2.getName(console.log).setName('Meow').getName(console.log);
// Displays 'Hello world' and then 'Meow'.
|