NO1
减少window查找时间和保护undefined变量,压缩时将undefined压缩成u,字节数减少
(function(window,undefined){
undefined=2;
alert(undefined);
})(window);
结果会是弹出2
undefined=2;
alert(undefined);
结果会弹出undefined
NO2
为了得到jQuery原型链上的方法
(function(window,undefiend){
var jQuery=function(select,context){
return new jQuery.fn.init(select,context);
}
jQuery.fn=jQuery.prototype={
init:function(selector,context){
}
}
jQuery.fn.init.prototype=jQuery.fn;
})(window);
jQuery插件扩展
jQuery.fn.extend({
a:function(){
console.log(123);
}
});
$('').a(); //123
jQuery.extend({
s:13
});
jQuery.s; //13
NO3
开始时$(".text")不存在,把事件都绑定到body上
$('body').append('<div class="text"></div>');
$('body).on('click','test',function(){
});
NO4
$('.test').val()取值,$('.test').val('test')赋值
function addMethod(obj,name,f){
//老的还是undefined
var old=obj[name];
//people[find]=function,给people加find方法
obj[name]=function(){
//f.length为find0传递过来的参数,此时find0没传参数所以为0,
//arguments.length为实参是people.find()穿的实参,所以为0.
if(f.length===arguments.length){
//f为find0,this是把people的指向f,f具有people的一些属性
return f.apply(this,arguments);
}else{
return old.apply(this,arguments);
}
}
}
var people={
name:["zhangsan","lisi","wangerma"]
}
var find0=function(){
return this.name;
}
addMethod(people,'find',find0);
people.find();
function addMethod(obj,name,f){
//old undefined obj.find->find0
//old find0 obj.find->find1
var old=obj[name];
obj[name]=function(){
if(f.length===arguments.length){
return f.apply(this,arguments);
}else{
return old.apply(this,arguments);
}
}
}
var people={
name:["zhangsan","lisi","wangerma"]
}
var find0=function(){
return this.name;
}
var find1=function(name){
var arr=this.name;
for(var i=0;i<=arr.length;i++){
if(arr[i]==name){
return arr[i]+'在'+i+'位';
}
}
}
addMethod(people,'find',find0);
addMethod(people,'find',find1);
console.log(people.find('lisi'));
console.log(people.find());
执行结果
lisi在1位
(3) ["zhangsan", "lisi", "wangerma"]
NO5
if(a){
var foo=a;
}else{
var foo=b;
}
//短路表达式
var foo=a||b;
a&&test()
NO6
勾子
$.each("Boolean Number String Function Array Date RegExp Object Error".split(""),function(i,name){
class3type["[object"+name+"]"]=name.toLowerCase();
});
>Object.prototype.toString.call({})
>"[object Object]"
>Object.prototype.toString.call([])
>"[object Array]"
NO7
onready
var $=ready=window.ready=function(fn){
if(document.addEventListener){//兼容非IE
document.addEventListener('DOMContentLoaded',function(){
//注销事件,避免反复触发
document.removeEventListener('DOMContentLoaded',arguments.callee,false);
fn();//调用参数函数
},false);
}else if(document.attachEvent){//IE
IEContentLoaded(window,fn);
}
function IEcontentLoaded(w,fn){
var d=w.document,done=false;
init=function(){
if(!done){
done=true;
fn();
}
}
//polling for no errors
(function(){
try{
//throws errors until after ondocumentready
d.documentElement.doScroll('left');
}catch(e){
setTimeout(arguments.callee,50);
return;
}
init();
})();
}
}
网友评论