【问题标题】:Express / Jade / Pug: Calling a javascript object's functionsExpress / Jade / Pug:调用 javascript 对象的函数
【发布时间】:2017-11-10 05:30:17
【问题描述】:

虽然我可以传递对象的数据,但我不知道如何传递/调用对象的函数。

route.js:

router.get('/', function(req, res, next) {
  let test = {}; // passing an object called test
  test.hello = function() { //the test object has a method I want to
    console.log('hello');   //call on the browser
  }

  res.render('home.jade', { test:test });

.jade 页面上:

//- let test = !{test}; //renders as [object Object]
    let test = !{JSON.stringify(test, null, 4)}; //renders empty obj
    test.hello();
    console.log('test', test);

控制台消息:

Uncaught TypeError: test.hello is not a function

渲染的源文件:

//- let test = [object Object];
let test = {};
test.hello();
console.log('test', test);

对 my.jade 文件有效的示例(我不想要的):

    let test = {};
    test.hello = #{test.hello};
    test.hello();

这将安慰出“你好”。但是,我想有一种方法可以在没有这种解决方法的情况下传递和调用对象的函数。

感谢您的帮助。

【问题讨论】:

    标签: node.js express pug


    【解决方案1】:

    JSON.stringify 将剥离函数,因为 JSON 格式不支持函数/方法。来自MDN

    函数不是有效的 JSON 数据类型,因此它们将不起作用。 但是,如果首先转换为字符串(例如在 替换器),通过函数的 toString 方法。还有一些对象 像 Date 将是 JSON.parse() 之后的字符串。

    从技术上讲,您可以使用 eval 将结果字符串评估为函数,但不建议这样做。

    【讨论】:

      猜你喜欢
      • 2021-11-20
      • 1970-01-01
      • 2018-06-28
      • 2017-06-10
      • 2016-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多