实现如下语法的功能:var a = add(2)(3)(4); //9
方法一:
var add = function(a){
return function(b){
return function(c){
return a+b+c;
};
};
};
add(1)(2)(3); //6
方法二:
function add(a){
var tmp = function(b){return add(a+b);}
tmp.toString=tmp.valueOf=function(){return a;}
return tmp;
}
var result = add(1)(2)(3)
console.log(result) // 会输出 function 6;
typeof add(1) // "function"
typeof add(1).toString() // "number"
alert(result) // 弹出数字 6
转化一个数字数组为function数组(每个function都弹出相应的数字)
function array2func(arr){
var i=0,len,result=[];
for(len=arr.length;i<len;i++){
var func = (function(value){
return function (){
console.log(value)
}
})(arr[i])
result.push(func)
}
return result;
}
function Observer() {
this.fns = []
}
Observer.prototype.subscribe = function(fn){
this.fns.push(fn)
}
Observer.prototype.unsubscribe = function(fn){
this.fns = this.fns.filter(function(item){
if(item !== fn){
return item
}
})
}
Observer.prototype.update = function(o,thisObj){
var scope = thisObj || window;
this.fns.forEach(function(itemFn){
itemFn.call(scope,o)
})
}
var observer = new Observer;
var fn1 = function(data){
console.log(data+'快点跑啊!')
}
var fn2 = function(data){
console.log(data+'做饭了!!!')
}
observer.subscribe(fn1)
observer.subscribe(fn2)
observer.update('二狗子')
var dom = {
on:function(node,eventType,handler){
if(node.addEveentLisen){
node.addEventListener(eventType,handler,false)
}else(
node.attachEvent('on'+eventType,handler)
)
},
off:function(node,eventType,handler){
if(node.removeEventLinstener){
node.removeEventLinstener(''eventType,handler,false)
}else{
node.detatchEvent('on'+eventType,handler)
}
},
//获取元素样式
getStyle:function(node,styleName){
var realStyle = null;
if(window.getComputedStyle){
realStyle = window.getComputedStyle(node,null)[styleName]
}else if(node.currentStyle){
realStyle = node.currentStyle[styleName]
}
return realStyle;
},
//设置元素样式
setCss:function(node,css){
for(var key in css){
if(css.hasOwnProprty(key)){
node.style[key] = css[key]
}
}
}
}