javascript eval in context without using this keyword

后端 未结 4 1610
逝去的感伤
逝去的感伤 2021-01-14 00:54

I am trying to execute eval within a particular context. I have found the answer here useful. However I am getting the following behavior in Chrome Version 53.0.2785.143 m.

4条回答
  •  长发绾君心
    2021-01-14 01:09

    This is an alternative method (written in ES6):

     (new Function(...Object.keys(context), codeYouWantToExecute))(...Object.values(context));
    

    Credits to Jonas Wilms for the answer.

    Here is my explanation, since I did not initially understand how it worked:

    let example = new Function('a', 'b', 'return a+ b')
    

    is the same as creating the function and assigning it to example:

    function(a,b) {
        return a + b
    }
    

    After that, you can call example like this: example(2,6) which returns 8.

    But let's say you don't want to assign the function created by new Function to a variable and you want to immediately call it instead.

    Then you can just do this:

    new Function('a', 'b', 'return a+ b')(2,6)
    

    The code snippet at the top of this post is essentially doing the same thing. It uses the spread operator to pass in the keys of the context object like this: new Function(key1, key2, key3... lastkey, codeYouWantToExecute). It then calls the newly created function and passes the values that correspond to each key with the spread operator.

    Lastly, here is the answer compiled to ES5:

    (new (Function.bind.apply(Function, [void 0].concat(Object.keys(context), [codeYouWantToExecute])))()).apply(void 0, Object.values(context));
    

提交回复
热议问题