let fn = (a, b, c) => {
console.log(a, b, c)
}
fn1(0, 0, 0) // output: 0 0 0
I want fn to always add 2 to the second parameter every time it is called
Right now
fn(0, 0, 0) // output: 0 2 0
fn(1, 1, 1) // output: 1 3 1
Currently I have only found a very ugly way to write hijack:
fn = (_ => {
const innerFn = fn
const newFn = (a, b, c) => {
innerFn(a, b + 2, c)
}
Object.assign(newFn, innerFn)
return newFn
})()
Is there a better packaging method?
淡淡烟草味2017-05-16 13:32:03
The method is correct, but I always feel that your writing is a bit awkward... I think it is better to be more direct...
// 原函数
function fn(a, b, c) {
console.log(a, b, c)
}
// 加工函数
const addTwo = (fn) =>
(a, b, c) =>
fn(a, b + 2, c);
// 生成新函数
const newFn = addTwo(fn);
newFn(0, 0, 0); //0 2 0
为情所困2017-05-16 13:32:03
I want fn to always add 2 to the second parameter every time it is called
In fact, it is nothing more than adding 0, 2, 0 to the parameters respectively
That is to say, another 偏函数
fnOffset
Add the three parameters [0, 2, 0] to a b c on fn(a, b, c) respectively
In a broader sense:
Place [ .... ]
这 n
个参数 分别加到 fn()
的 arguments
at the corresponding position
function fn(a, b, c){
console.log(a, b, c);
}
function adder(arr, fn, _this){
_this = _this || window;
var toAdd = arr.slice(0, fn.length);
return function(){
var argu = Array.prototype.slice.call(arguments);
fn.apply(_this, toAdd.map((item, idx) => {
return argu[idx] + item;
}));
}
}
var fnOffset = adder([0, 2, 0], fn);
fnOffset(0, 0, 0);
fnOffset(2, 1, 0);
It should be more elegant to use fn020
as variable name = =
ringa_lee2017-05-16 13:32:03
What you describe is a bit like ES6’s Proxy, but this cannot be polyfilled and may not be suitable for use on the front end.