【问题标题】:JavaScript Bind, Apply, and the `this` pointerJavaScript Bind、Apply 和 `this` 指针
【发布时间】:2023-03-11 02:11:02
【问题描述】:

我对 JS bindapplythis 有点困惑。

问题

  • 为什么 thisnull 在下面的 sn-p 中可以互换?
  • 以下上下文中的this 是否指向window

function curry(fn) {
  // your code here
  return function curryInner(...args) {
    if (args.length >= fn.length) return fn.apply(this, args);
    return curryInner.bind(this, ...args);  //change this to null, still pass the test
  };
  
}
const join = (a, b, c) => {
   return `${a}_${b}_${c}`
}

const curriedJoin = curry(join)

console.log(curriedJoin(1, 2, 3)) // '1_2_3'

【问题讨论】:

    标签: javascript currying


    【解决方案1】:

    不,this 指向它所在函数的 this 上下文。

    在这种情况下,你放什么并不重要,因为调用 bind 的唯一目的是创建一个已设置 args 的函数副本。

    return curryInner.bind(null, ...args)
    

    基本上可以替换为

    return function() {
      return curryInner(args);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-17
      • 2011-06-19
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多