下划线的简单错误

时间:2013-03-29 22:56:31

标签: javascript web-services backbone.js underscore.js

请有人告诉我为什么下面的第1行会引发错误

Uncaught TypeError: Cannot read property 'age' of undefined.

我是javascript和骨干的新手,这个错误对我来说毫无意义。

谢谢

<script>
var Person = Backbone.Model.extend({
    initialize: function(){
        console.log("Person is initialized");
    }
});

var People = Backbone.Collection.extend({
    model: Person,

    initialize: function(){
        console.log("People model is initialized");
    }
});

var person = new Person({age: 12});
var person2 = new Person({age: 15});
var person3 = new Person({age: 12});
var people = new People();
people.add(person);
people.add(person2);

// (1) var ages = _.where(people, {age: 12});
console.log(ages); 
</script>

1 个答案:

答案 0 :(得分:1)

好像你想要这个:

var ages = people.where({age: 12});

Underscore's whereBackbone Collection's where是两回事。

就像Fabricio所说,错误意味着一些代码试图读取未定义的属性。像foo.age foo undefined之类的内容会产生此错误。

由于您说您不熟悉javascript ...在Chrome开发工具中,您可以点击错误,它会将您带到错误发生的位置。在这种情况下,它需要您强调源代码。当库中发生错误时,99%的时间(如果库被广泛使用),这意味着您使用了错误的东西,并且可以检查文档以查看发生了什么。