//jquery使用的就是块级作用域
//特点1.块级作用域的作用就是程序启动时,直接执行了
//特点2.内部的成员变量,外部无法访问
(function(Window,undefined){
// $ 最常用的对象,返回给外界,等于出口,一般大型程序当中 _ 作为私有对象(规范)
function _$(arguments){
//实现代码....
//正则表达式,匹配ID
var idselector = /#\w+/;
//此属性接受所得到的元素
this.dom;
if(idselector.test(arguments[0])){
//如果匹配则成功,则接受dom元素
this.dom = document.getElementById(arguments[0].substring(1));
}else{
throw new Error('arguments it error');
}
}
//在Function类上扩展一个可以实现链式变成的方法
//参数1:链式方法的名字
//参数2:函数
Function.prototype.method = function(methodName,fn){
//_$原型
this.prototype[methodName] = fn;
//链式变成的关键
return this;
}
//在_$上通过原型,增加公共的方法
_$.prototype = {
constructor : _$,
addEvent : function(type,fn){
//console.log('addEvent');
//给得到的元素添加事件
if(window.addEventListener){
this.dom.addEventListener(type,fn);
}else if(window.attachEvent){
this.dom.attachEvent('on'+type,fn);
}
return this;
},
colorStyle : function(key,value){
//console.log('colorStyle');
this.dom.style[key] = value;
return this;
}
}
//window上先注册一个全局变量,与外界产生联系,外界可以访问
window.$ = _$;
//写一个准备方法,在_$绑定一个方法
_$.onReady = function(fn){
//1.实例化出来_$对象,真正的注册到window上
window.$ = function(){
return new _$(arguments);
};
//2.执行传入进来的代码,onReady函数里传入的
fn();
//3.实现链式编程
_$.method('addEvent',function(){
}).method('colorStyle',function(){
});
}
})(window);//window等于程序的入口,传入作用域中
//运行
$.onReady(function(){
var inp = $('#input');
//var domObject = inp.get(0);
//console.log(inp.dom);
//alert(inp.dom);
inp.addEvent('click',function(){
console.log('我执行了');
}).colorStyle('backgroundColor','#ff6699');
});
实现jQuery底层链式编程(二)
最新推荐文章于 2021-08-05 14:11:07 发布