基于原型继承的链模式

来源:互联网 发布:51单片机控制电机 编辑:程序博客网 时间:2024/06/05 18:04
var A = function(selector,context){
return new A.fn.init(selector,context);
}
A.fn = A.prototype = {
constructor:A,
init:function(selector,context){
this.length = 0 ;
context = context||document;
if(~selector.indexOf('#')){
this[0] = document.getElementById(selector.slice(1));
this.length = 1;
}else{
var doms = context.getElementsByTagName(selector),i = 0 ,len = doms.length;
for(; i < len; i ++){
this[i] = doms[i];
}
this.length = len;
}
this.context = context;
this.selector = selector;
return this;
},
length : 2,
size:function(){
return this.length;
},
push:[].push,
sort:[].sort,
splice:[].splice
}
A.fn.init.prototype = A.fn;
console.log(A('demo'));
A.extend = A.fn.extend = function(){
var i = 1 , len = arguments.length,target = arguments[0],j;
if(i == len){
target = this;
i--;
}
for(; i < len ; i ++){
for(j in arguments[i]){
target[j] = arguments[i][j];
}
}
return target;
}
A.fn.extend({
camelCase:function(str){
return str.replace(/\-(\w)/g,function(all,letter){
return letter.toUpperCase();
})
},
css:function(){
var arg = arguments,
len = arg.length;
if(this.length < 1){
return this;
}
if(len == 1){
if(typeof arg[0]==='string'){
if(this[0].currentStyle){
return this[0].currentStyle[name];
}else{
return getCumputedStyle(this[0],false)[name];
}
}else if(typeof arg[0]==='object'){
for(var i in arg[0]){
for(var j = this.length -1 ; j >= 0 ; j--){
this[j].style[this.camelCase(i)] = arg[0][i];
}
}
}
}else if(len === 2){
for(var j = this.length -1 ; j >= 0 ; j --){
this[j].style[this.camelCase(arg[0])] = arg[1];
}
}
return this;
},
attr:function(){
var arg = arguments,
len = arg.length;
if(this.length < 1){
return this;
}
if(len === 1){
if(typeof arg[0]==='string'){
return this[0].getAttribute(arg[0]);
}else if(typeof arg[0]==='object'){
for(var i in arg[0]){
for(var j = this.length - 1 ; j >= 0 ; j --){
this[j].setAttribute(i,arg[0][i])
}
}
}
}else if(len === 2){
for(var j  = this.length -1 ; j >=0 ; j --){
this[j].setAttribute(arg[0],arg[1]);
}
return this;
}
},
html:function(){
var arg = arguments,
len = arg.length;
if(len === 0){
return this[0]&&this[0].innerHTML;
}else{
for(var j = this.length -1 ; j >= 0 ; j--){
this[j].innerHTML = arg[0]
}
}
return this;
},
on:(function(){
if(document.addEventListener){
return function(type,fn){
var i = this.length -1;
for(; i >= 0 ; i --){
this[i].addEventListener(type,fn,false);
}
return this;
}
}else if(document.attachEvent){
return function(type,fn){
var i = this.length - 1;
for(; i >= 0 ;i --){
this[i].addEvent('on' + type,fn);
}
return this;
}
}else{
return function(type,fn){
for(; i >= 0 ;i --){
this[i].addEvent('on' + type,fn);
}
return this;
}
}
})()
})
var demo = A('div');
console.log(demo);
A('div').css({height:'30px',border:'1px solid #000'}).attr('class','demo').html('add demo text')
.on('click',function(){
console.log('clicked');
})
0 0
原创粉丝点击