简体   繁体   English

消除了在call()调用的函数内部编写“ this”的需要?

[英]Eliminating the need to write 'this' inside function being called by call()?

I want to be able to write expressions as strings and then evaluate them. 我希望能够将表达式编写为字符串,然后对其求值。 So I have: 所以我有:

var expression  = "this.num*2"
function x(expression, o) {
  var fn = function(){}, result;
  fn = Function.apply(o, ["return " + expression + " ;"]);
  return fn.call(o)
}

var obj = {"num":3}
console.log(x(expression, obj))

Which works great. 哪个很棒。 However, I want to be able to write "num*2" 但是,我希望能够写“ num * 2”

How do I do this? 我该怎么做呢?

您可以尝试使用JavaScript Expression Evaluation库 ,该允许执行Parser.evaluate("num * 2", {num: 3})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在调用apply()或call()时,“ this”指向函数内部的窗口? - Why 'this' points to window inside a function when apply() or call() is being called? Nodejs-不从成功的请求调用内部调用递归函数 - Nodejs- Recursive function not being called from inside a successful request call 插件函数内部的setInterval()未被调用 - setInterval() inside plugin function not being called 另一个函数内部的函数调用未执行 - Function call inside another function not being executed 在ng-repeat内部的表达式中调用的Angularjs函数没有被调用吗? - Angularjs function called in an expression inside ng-repeat is not being called? 消除有关函数内部样式更改的 else 语句 - Eliminating else statement on style changes inside function Jestjs如何测试在另一个函数中被调用的函数 - Jestjs how to test function being called inside another function function 中的 for 循环在另一个函数的 for 循环 javascript 中被调用 - for loop inside a function being called in another function's for loop javascript Ajax function 内秒成功 function 未被调用 - Ajax function inside a second Success function is not being called 为什么在函数内部不调用Google Chart函数? - Why is google chart function not being called when it's inside a function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM