Express / Jade / Pug:调用JavaScript对象的函数
虽然我可以传递对象的数据,但我不知道如何传递/调用对象的函数。
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();
这将安慰'你好'。 不过,我想象有一种方法可以传递并调用一个对象的函数,而不需要这个解决方法。
谢谢你的帮助。
由于JSON格式不支持函数/方法,因此JSON.stringify
将剥离函数。 来自MDN :
函数不是有效的JSON数据types,所以它们不能工作。 但是,如果首先通过函数的toString方法将其转换为string(例如在replace器中),则可以显示它们。 此外,像Date这样的对象将是JSON.parse()之后的string。
从技术上讲,你可以使用eval
来评估eval
的结果string,尽pipe这不被推荐。