javascript 精粹笔记
人气:0
//为构造函数原型添加方法
Function.method=function(name,func){
this.prototype.name=func;
}
Number.method("integer",function(){
return Math[this < 0 ? 'ceil':'floor'](this);
});
(-10/3).integer();//-3
String.method("trim",function(){
return this.replace(/^\s+|\s+$/g,'');
})
" neat ".trim();//neat
//闭包
var quo = function(status){
return{
get_status:function(){
return status;
}
}
}
var myQuo = new quo("amazed");
myQuo.get_status();//amazed
//闭包经典例子片段
for(var i=0;i<lis.length;i++){
lis.onclick=function(i){
return function(){
alert(i);
};
}(i);
}
//套用
Function.method("curry",function(){
var slice=Array.prototype.slice,
args = slice.apply(arguments),
that = this;
return function(){
return that.apply(null,args.contact(arguments));
}
})
//记忆 递归
var memoization = function(memo,usefn){//抽象化
var fn = function(n){
var result = memo[n];
if(typeof result!=='number'){
result=usefn(fn,n);
memo[n]=result;
}
return result;
};
return fn;
};
var factorial= memoization([0,1],function(fn,n){//递归的形式
return fn(n-1)*n
});
factorial(5)//120
Function.method=function(name,func){
this.prototype.name=func;
}
Number.method("integer",function(){
return Math[this < 0 ? 'ceil':'floor'](this);
});
(-10/3).integer();//-3
String.method("trim",function(){
return this.replace(/^\s+|\s+$/g,'');
})
" neat ".trim();//neat
//闭包
var quo = function(status){
return{
get_status:function(){
return status;
}
}
}
var myQuo = new quo("amazed");
myQuo.get_status();//amazed
//闭包经典例子片段
for(var i=0;i<lis.length;i++){
lis.onclick=function(i){
return function(){
alert(i);
};
}(i);
}
//套用
Function.method("curry",function(){
var slice=Array.prototype.slice,
args = slice.apply(arguments),
that = this;
return function(){
return that.apply(null,args.contact(arguments));
}
})
//记忆 递归
var memoization = function(memo,usefn){//抽象化
var fn = function(n){
var result = memo[n];
if(typeof result!=='number'){
result=usefn(fn,n);
memo[n]=result;
}
return result;
};
return fn;
};
var factorial= memoization([0,1],function(fn,n){//递归的形式
return fn(n-1)*n
});
factorial(5)//120
加载全部内容