i'm getting unexpected behavior out of mongoose: when use model.create argument in mapping function, receive error
variables.map(variable.create); typeerror: object not function @ array.foreach (native) @ array.map (native)
but when wrap model.create in anonymous function, don't receive error:
variables.map(function(variable) { return variable.create(variable); });
what gives?
using "node": "0.10.33"
, "mongoose": "3.8.25"
ah, you've stumbled world of javascript objects , methods/properties.
the short answer internally method create
uses other object properties/methods variable
. when pass variable.create
mapping function passes reference create
directly , prototype chain broken. if want way use bind
bind it's parent object:
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 = 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' global scope here this.word === word say(); // hello
for long answer recommend reading you don't know js: & object prototypes.
Comments
Post a Comment