javascript - js Is there an elegant way to input parameters from external hijack function?
黄舟
黄舟 2017-05-16 13:30:03
0
3
459
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?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
淡淡烟草味

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
为情所困

I want fn to always add 2 to the second parameter every time it is called

Uh-huh. .

In fact, it is nothing more than adding 0, 2, 0 to the parameters respectively

That is to say, another 偏函数 fnOffset

is generated from function fn

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 = =

左手右手慢动作

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template