基于Underscore的迭代器原型没有获得价值

时间:2014-01-29 14:03:08

标签: javascript underscore.js

使用下划线,我迭代数据,并添加到函数中,在我添加之后,我使用'prototype'扩展函数 - 当我调用该原型时我没有得到任何价值。并且原型根本不可供公众使用..

这是我的代码:

var 
data = {
    people : [
        {name:'Caring', state:'Tn', price:'100'},
        {name:'Mo', state:'Ap', price:'200'},
        {name:'af', state:'Jk', price:'33'},
        {name:'adi', state:'Kl', price:'400'},
        {name:'Hu', state:'Ka', price:'600'}
    ]
},

    OrderItem = function(person){
        this.person = person
        getSummary = function(){
          return  person.name
            + ' spent '
            + person.price
            + ' in ' + person.state + '.';
        }

        return {getSummary : getSummary}
    };

    OrderItem.prototype.data = function(){
        return this.person;
    }

    m = _.collect(data.people, function(value, key, list){
        return new OrderItem(value);
    })



_.each(m, function(value){
   // console.log(value.getSummary()); //works fine
    console.log(value.data()); //not working!
})

在_.each方法中,当我调用value.data时,我收到错误。如何解决这个问题?

DEMO HERE

1 个答案:

答案 0 :(得分:1)

您只返回getSummary方法。 为什么不使用this

jsfiddle

OrderItem = function(person){
    this.person = person
    getSummary = function(){
      return  person.name
        + ' spent '
        + person.price
        + ' in ' + person.state + '.';
    }

    return this;
};