Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

柯里化函数内部实现问题

function sub_curry(fn) {
    console.log(arguments)
    console.log(fn)
    let args = Array.prototype.slice.call(arguments, 1)
    return function () {
        let newArgs = args.concat(Array.prototype.slice.call(arguments))
        return fn.apply(this, newArgs)
    }
}

function curry(fn, length) {
    // 获取需要柯里化函数的参数长度
    length = length || fn.length;
    var slice = Array.prototype.slice;
    return function () {
        if (arguments.length < length) {
            let combined = [fn].concat(slice.call(arguments));
            console.log("combined:", combined)
            return curry(sub_curry.apply(this, combined), length - arguments.length);
        } else {
            return fn.apply(this, arguments)
        }
    }
}

在sub_curry中
console.log(arguments)和console.log(fn)为什么不同?
fn为何为一个函数不应该是下方的combined数组吗?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. argument[0] === fn
  2. apply 的第二个参数为数组,数组成员会被“摊开”后作为被 apply 的函数参数列表:
fn.apply(null, [a, b, c]);

基本等同于:

fn(a, b, c);

说它们“基本等同”是因为 this 指向不一样。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...