calling eval() in particular context

前端 未结 14 1030
说谎
说谎 2020-11-27 17:05

I have following javaScript \"class\":

A = (function() {
   a = function() { eval(...) };
   A.prototype.b = function(arg1, arg2) { /* do something... */};
}         


        
相关标签:
14条回答
  • 2020-11-27 18:11

    What worked for me was using Function constructor and calling it in specified context:

    var o = {
      x: 10
    }
    
    (new Function(`console.log(this.x)`)).call(o);

    This somehow doesn't work in browser's console but works elsewhere.

    0 讨论(0)
  • 2020-11-27 18:12

    You can use my library https://github.com/marverix/meval .

    const meval = require('meval');
    
    console.log(
      meval('item.a + item.b * 5', { item: { a: 2, b: 3 } })
    );
    
    // outputs: 17
    
    0 讨论(0)
提交回复
热议问题