Node Mongoose TypeError:object 不是具有 Array.map 和 Model.create



我从猫鼬中得到了一些意外的行为:当我使用Model.create作为映射函数中的参数时,我收到一个错误

variables.map(Variable.create);
TypeError: object is not a function
at Array.forEach (native)
at Array.map (native)

但是当我将 Model.create 包装在匿名函数中时,我没有收到错误:

variables.map(function(variable) {
return Variable.create(variable);
});

什么给?

使用"node": "0.10.33""mongoose": "3.8.25"

啊,你偶然进入了Javascript对象及其方法/属性的世界。

简短的回答是内部使用Variable中的其他对象属性/方法的方法create。当您将Variable.create传递给映射函数时,它会直接传递对create的引用,因此原型链现在已断开。如果你真的想这样做,你可以使用bind将其绑定回它的父对象:

variables.map(Variables.create.bind(Variables));

var objA = {
word: 'bar',
say: function() {
alert(this.word);
}
};
var objB = {
word: 'foo',
say: function() {
alert(this.word);
}
};
var say = objA.say;
var bound = objA.say.bind(objB);
objA.word; // bar
objA.say(); // bar
objB.word; // foo
objB.say(); // foo
say(); // undefined --> this.word
bound(); // foo
// bonus fun
word = 'hello'; // 'this' is the global scope here so this.word === word
say(); // hello

对于长答案,我建议阅读You Don't Know JS: this & Object Prototypes

最新更新