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

Categories

0 votes
3.5k 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 Answer

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

基本等同于:

fn(a, b, c);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.5k users

...