JavaScript学习笔记-函数实例
函数实例
var p = {
a:15,
b:'5',
f1:function(){
var self = this;
console.log(self.a+self.b);
f2();
function f2(){
console.log(self.a-self.b);
}
return self; //返回this,方便对对象p进行链式调用
},
m1:function(n1,n2){
this.a = n1>this.a?n1:this.a;
this.b = n2>this.b?n2:this.b;
return this;
}
};
p.m1('23','r').f1();
//=======sum()可接收任意个数,任意类型参数,将有效数字求和,若为不可计算对象设为0==========
function sum(){
var arg = arguments.length;
var sum = 0;
for(var i = 0;i<arg;i++){
var s = Object.prototype.toString.call(arguments[i]).slice(8,-1);
if(s === 'Number'||s ==='String'||s ==='Boolean'||s ==='Array'){
arguments[i] =
arguments[i] - 0 ||
Array.prototype.reduce.call(
arguments[i],
function (x, y) {
x = x - 0 || 0;
y = y - 0 || 0;
return x + y;
}) ||
0;
sum += arguments[i];
}
else {
sum += 0;
}
}
return sum;
}
var a = 'b3c',b = 4,c = true,d=[,5,'q'];
var num1 = {a:1,b:2,c:3,d:'m'};
console.log('数字求和等于: '+sum(c,num1,a,b,d,/./));
console.log(a);
//====
function sum1(a){
var total = 0;
for(var i = 0;i<arguments.length;i++){
var a = arguments[i],n;
if(a==null) continue;
if(Array.isArray(a)) n = sum1.apply(this,a);
else if(typeof a === 'function') n = Number(a());
else n = Number(a);
total += n;
}
return total;
}
console.log(sum1([9,8,7,'6'],4));
//=====
var operators = {
add:function(a,b){return a+b;},
substract:function(a,b){return a-b;},
multiply:function(a,b){return a*b;},
divide:function(a,b){return a/b;},
pow:Math.pow
};
function operate(operator,a,b){
if(typeof operators[operator]==='function')
return operators[operator](a,b);
else throw new Error('unknown operator!');
}
console.log(operate('divide',20,4));
//=====
(function(){
console.log('这里立即执行函数');
}());
//======特定场景下返回不同版本的extend或者extend2
var extend = (function(){
for(var p in {toString:null}){
return function extend(o){
for(var i=1;i<arguments.length;i++){
var source = arguments[i];
for(var prop in source) o[prop] = source[prop];
}
return o;
};
}
var protoprops = ['toString','valueOf','constructor','hasOwnProperty','isPropertyOf','propertyIsEnumerable','toLocaleString'];
return function extend2(o){
for(var i=1;i<arguments.length;i++){
var source =arguments[i];
for(var prop in source) o[prop] = source[prop];
for(var j=0;j<protoprops.length;j++){
prop = protoprops[j];
if(source.hasOwnProperty(prop)) o[prop] = source[prop];
}
}
return o;
};
}());
var b1 = {a:1,b:2},b2 = {c:3,d:4};
console.log(extend); //[Function: extend]
console.log(extend(b1,b2)); //{ a: 1, b: 2, c: 3, d: 4 }
//=====
var uniq = (function(){
var c = 0;
return function(){return c++;};
}());
console.log(uniq());//0
console.log(uniq());//1
//=====无法从外部访问闭包内的局部变量,只有闭包内的方法可以访问
function couter(){
var c=0;
return {
count: function() {return ++c;},
reset: function() {return c=0;}
};
}
var couter1 = couter() , couter2 = couter(); //创建不同的函数对象,他们互不干扰
console.log(couter1.count());//1
console.log(couter2.count());//1
console.log(couter1.reset());//0
console.log(couter1.count());//1
console.log(couter2.count());//2
//=========
function addPrivateProperty(o,name,predicate){
var value;
o['get'+name] = function(){return value;};
o['set'+name] = function(v){
if(predicate && !predicate(v)){
throw Error('set'+name+':invalide value '+v);
}else value = v;
};
}
var o = {};
addPrivateProperty(o,'Name',function(x){return typeof x == 'string';});
o.setName('Frank');
console.log(o);
//=========面向对象的模块化编程(初探)======
var Module = (function(){
var myModule = {}; //创建私有对象,被返回后变公共对象
var _privateMethod = function(){return '_private';}; //私有方法
myModule.publicMethod1 = function(){console.log('content a '+_privateMethod()+' and myself public_By_myModule');};
var publicMethod2 = function(){console.log('public_By_return');};
return{
myModule:myModule,
publicMethod2:publicMethod2,
publicMethod3:function(){console.log('public');}
}
})();
Module.myModule.publicMethod1();
Module.publicMethod2();
Module.publicMethod3();
//=============bind()
var sum3 = function(x,y){return x+y;};
var succ = sum3.bind(null,1); //x=1
succ(2); //3,其中y=2
function f(x,y,z){return this.x+y+z;}
var g = f.bind({x:1},2); //x=1,y=2
g(3); //6,z=3
f.bind({x:1},2,3)(); //6,立即执行函数
//======函数式编程:单独定义一些重复利用的基础功能函数并保存为变量,然后在实际应用中引用他们
var sum4 = function(x,y){return x+y;};
var square = function(x){return x*x;};
var data = [1,1,3,4,4];
var mean = data.reduce(sum4)/data.length;
var deviations = data.map(function(x){return x-mean;});
var stddev = Math.sqrt(deviations.map(square).reduce(sum4)/(data.length-1));
function compose(f1,f2){
return function(){return f1.call(this,f2.apply(this,arguments));};
}
compose(square,sum4)(2,3); //25
//======
//=====不完全函数f的调用:
function array(a,n){return Array.prototype.slice.call(a,n||0);}
var f = function(x,y,z){return x*(y-z)};
function partialLeft(f /*,...*/){
var args = arguments;
return function(){
var a = array(args,1);
a = a.concat(array(arguments));
return f.apply(this,a);
};
}
console.log( partialLeft(f,2)(3,4) ); //-2, 其中a=[2,3,4]
function partialRight(f /*,...*/){
var args = arguments;
return function(){
var a = array(arguments);
a = a.concat(array(args,1));
return f.apply(this,a);
};
}
console.log( partialRight(f,2)(3,4) ); //6,其中a=[3,4,2]
function partial(f /*,...*/){
var args = arguments;
return function(){
var a = array(args,1);
var i = 0, j = 0;
for(;i< a.length;i++){
if(a[i] === undefined) a[i] = arguments[j++]; //每次循环后,若if条件为true,j也+1
}
a = a.concat(array(arguments,j));
return f.apply(this,a);
};
}
console.log(partial(f,2,undefined,3)(5,9)); //4,其中a=[2,5,3]
//======缓存技术的应用:检查要计算的参数,看是否在缓存内有用同样的参数计算过,若有则返回缓存的计算结果,避免重复计算
function memorize(){
var cache = {}; //用来缓存的对象
return function (f) {
var args = Array.prototype.slice.call(arguments,1);
var key = arguments.length-1 + ':' + f + args.join('-');
if (key in cache) return cache[key];
else {
cache[key] = f.apply(this,args); //若缓存内不存在key,则创建这个key并赋值
console.log(cache);
return cache[key];
}
};
}
var add = function(x,y){return x+y;};
var divide = function(x,y){return x-y;};
var memo = memorize();
memo(add,4,5);
memo(Math.pow,4,5);
memo(divide,4,5);
//===
function memorize2(f){
var cache2 = {};
return {
cheakMemo:function() {
var key = arguments.length + ':(' + Array.prototype.join.call(arguments, ',') + ')';
if (key in cache2) return cache2[key];
else {
cache2[key] = f.apply(this, arguments);
console.log(cache2);
return cache2[key];
}
},
cache2:cache2
};
}
var memo = memorize2(add);
memo.cheakMemo(4,5); //{ '2:(4,5)': 9 }
memo.cheakMemo(4,5); //直接取缓存的值,不计算
memo.cheakMemo(4,6); //{ '2:(4,5)': 9, '2:(4,6)': 10 }
memo.cheakMemo(4,7); //{ '2:(4,5)': 9, '2:(4,6)': 10, '2:(4,7)': 11 }
读完觉得学到点什么,就( 顶一个!)
posted on 2016-07-25 23:26 SuriFuture 阅读(176) 评论(0) 编辑 收藏 举报