Express/Jade/Pug:调用javascript对象的函数 [英] Express / Jade / Pug: Calling a javascript object's functions
问题描述
虽然我可以传递对象的数据,但我不知道如何传递/调用对象的函数.
While I can pass an object's data, I don't know how to pass/call an object's functions.
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();
这将消除"hello".但是,我认为没有这种解决方法,就有一种方法可以传递和调用对象的函数.
This will console out 'hello'. However, I imagine that there is a way to pass and call an object's function without this workaround.
感谢您的帮助.
推荐答案
JSON.stringify
将剥离函数,因为JSON格式不支持函数/方法.来自 MDN :
JSON.stringify
will strip away functions since JSON format does not support functions/methods. From MDN:
函数不是有效的JSON数据类型,因此它们将不起作用. 但是,如果先转换为字符串(例如, 通过该函数的toString方法).另外,一些物体 例如Date将是JSON.parse()之后的字符串.
Functions are not a valid JSON data type so they will not work. However, they can be displayed if first converted to a string (e.g. in the replacer), via the function's toString method. Also, some objects like Date will be a string after JSON.parse().
从技术上讲,您可以使用eval
将结果字符串评估为函数,尽管不建议这样做.
Technically you can use eval
to evaluate the resulting string to a function, though this is not recommended.
这篇关于Express/Jade/Pug:调用javascript对象的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!