Javascript - 对象的属性由函数决定,节点不等待它



我有一个相当简单的javascript/jquery对象正在构建的Node.js刮板。一切都正常工作(obj.prod_name_select和它的对应物返回jquery选择器,它们在Node中解析得很好)。

对象:

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' }

这是异步问题吗?看起来console.log发生在属性函数运行之前。解决这个问题的最好方法是什么?

不只是赋值函数,而是必须立即执行它:

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

最新更新