javascript:通过原型向方法添加行为-渗透代码

问题描述 投票:0回答:1

我们有以下情况,我们使用库对内容进行加密,我想知道是否可以在加密参数之前更改参数。我可以轻松做到这一点:

MyEncoder.prototype.encode = (value) => {//change it the way I want};

但是,在更改之前,我该如何做使其像以前一样? (我知道!!!

这将不起作用:var encoder = MyEncoder.prototype.encode;,因为它将仅复制方法,没有this,而且,您知道的。

如果可以调试encode方法。这会有所帮助!

javascript methods interceptor control-flow modifier
1个回答
0
投票

写一个立即调用的函数表达式(IIFE),它首先在它确实创建的闭包中保留了原始原型encode功能,然后第二次返回您自己的encode实现,该实现现在处于控制中传递的参数和原始encode的返回值。因此,有人写了一种around 方法修饰符 ...

MyEncoder.prototype.encode = (function /*create_around_modifier*/ (proto_encode) {
  return function /*modified_encode*/ (...argsArray) {

    // - intercept data flow ...
    //   ... e.g. look into or change the passed arguments.

    // ... implement the **before** part.

    // - call/invoke the original encode ...
    //
    // return value after invoking the original `encode`.
    const result = proto_encode.apply(this, argsArray);

    // - intercept data flow ...
    //   ... e.g. look at, work with or change the result.

    // ... implement the **after** part.

    //
    // - do not forget the return value.
  };
}(MyEncoder.prototype.encode));
© www.soinside.com 2019 - 2024. All rights reserved.