Is there a reason why `this` is nullified in Crockford's `curry` method?

后端 未结 4 629
遇见更好的自我
遇见更好的自我 2021-01-31 20:18

In Douglas Crockford\'s book \"Javascript: The Good Parts\" he provides code for a curry method which takes a function and arguments and returns that function with

4条回答
  •  盖世英雄少女心
    2021-01-31 20:37

    Reason 1 - not easy to provide a general solution

    The problem is that your solution is not general. If the caller doesn't assign the new function to any object, or assigns it to a completely different object, your multiplyPi function will stop working:

    var multiplyPi = myCalc.multiply.myCurry(Math.PI);
    multiplyPi(1);  // TypeError: this.history.concat is not a function
    

    So, neither Crockford's nor your solution can assure that the function will be used correctly. Then it may be easier to say that the curry function works only on "functions", not "methods", and set this to null to force that. We might only speculate though, since Crockford doesn't mention that in the book.

    Reason 2 - functions are being explained

    If you asking "why Crockford didn't use this or that" - the very likely answer is: "It wasn't important in regard to the demonstrated matter." Crockford uses this example in the chapter Functions. The purpose of the sub-chapter curry was:

    • to show that functions are objects you can create and manipulate
    • to demonstrate another usage of closures
    • to show how arguments can be manipulated.

    Finetuning this for a general usage with objects was not purpose of this chapter. As it is problematic if not even impossible (see Reason 1), it was more educational to put there just null instead if putting there something which could raise questions if it actually works or not (didn't help in your case though :-)).

    Conclusion

    That said, I think you can be perfectly confident in your solution! There's no particular reason in your case to follow Crockfords' decision to reset this to null. You must be aware though that your solution only works under certain circumstances, and is not 100% clean. Then clean "object oriented" solution would be to ask the object to create a clone of its method inside itself, to ensure that the resultant method will stay within the same object.

提交回复
热议问题