Javascript – 对象的属性是由一个函数决定的,节点不在等待它

我有一个相当简单的JavaScript / jQuery的obeject由一个Node.js刮刀build立。 一切工作,因为它应该( obj.prod_name_select和其对手返回jqueryselect器,他们parsing就好了在节点)。

这是对象:

 var product = { name : $(obj.prod_name_select).text(), systemName : function(){ return product.name.replace(/\s+/g, ' '); }, gender : obj.gender, infoLink : link, designer : $(obj.label_name_select).first().text(), description : function(){ var text = $(obj.description).each(function() { var content = $(this).contents(); $(this).replaceWith(content); }); return text; }, price : $(obj.price_select).first().text(), store : obj.store, category : obj.general_cat, spec_cat : obj.spec_cat } console.log(product); 

当我用Node运行这个时, 除了由函数设置的属性之外 ,它都工作正常。 这些返回节点中的[FUNCTION] 。 这是从控制台的日志:

 { name: 'BAGGY PANTS!T', systemName: [Function], gender: 'men', infoLink: 'http://www.hereisthecorrecturl.com', designer: 'Fancy Designer', description: [Function], price: '$180.00', store: 'Correct Store Name', category: 'Correct Category', spec_cat: 'Correct Category' } 

这是一个asynchronous的问题? 好像console.log是在属性函数运行之前发生的。 什么是解决这个问题的最好方法?

而不是只分配函数,你必须立即执行它 :

 description : (function(){ return $(obj.description).each(function() { var content = $(this).contents(); $(this).replaceWith(content); }); }()),