- 方法一
const calObject = function () {
this.num = 0
this.add = function (n) {
this.num = this.num + n
return this
}
this.valueOf = function(){
return this.num
}
}
let obj = new calObject()
console.log(+obj.add(3).add(4)) // 7
console.log(obj.add(3).add(4)==7) // ture
- 方法二
const calObj = function(){
let num = 0;
let add = function(number){
num += number;
return add;
}
add.valueOf = function(){
return num
}
return {add}
}
const co = calObj();
console.log(+co.add(1)(3)(5)) // 9
- 方法三
let add = function(num){
let temp = function(number){
num += number
return temp
}
temp.valueOf = function(){
return num
}
return temp
}
console.log(+add(1)(3)(3)) // 7
console.log(add(1)(3)(3).valueOf()) // 7
- 方法四
const add = function(num){
let temp = function(number){
return add(num + number)
}
temp.valueOf = function(){
return num
}
return temp
}
console.log(+add(1)(3)(5)) // 9
- 方法五
function add(...arg) {
temp = function(...tempArg){
if (tempArg.length === 0){
return arg.reduce( (num,number) => num + number )
}else{
[].push.apply(arg, tempArg)
return temp
}
}
return temp
}
console.log(add(1)(2)(3)())
繼承、閉包陪踩、遞歸掉奄、柯里化
相關(guān)文章