javascript - Unexpected results from the Underscore.js _.where method -


from documentation of underscore.js

_.where(list, properties);

looks through each value in list, returning array of values contain of key-value pairs listed in properties.

essentially give object list, , pass 'key-value pairs' properties. 'key-value pairs/properties' markers use tell where pull out , return.

that being said, tried following:

var obj = {     innerobj1 : {                    speak: function(){console.log('my name ' + name);},                    name: "tiger",                    space: 7                 },      innerobj2 : {                   speak: function(){console.log('my name ' + name);},                    name: "tiger2",                    space: 1                 },      inneronj3 : {                   speak: function(){console.log('my name ' + name);},                    name: "tiger3",                    space: 3},      innerobj4 : {                  speak: function(){console.log('my name ' + name);},                   name: "tiger4",                   space: 3} }; 

this returns:

_.where(obj,{speak:function(){console.log('my name ' + name);}}); [] //returns empty array, what?! 

vs.

function speak(){console.log('my name ' + name);}    var obj = {     innerobj1 : {                    speak: speak,                    name: "tiger",                    space: 7                 },      innerobj2 : {                   speak: speak,                    name: "tiger2",                    space: 1                 },      inneronj3 : {                   speak: speak,                    name: "tiger3",                    space: 3},      innerobj4 : {                   speak: speak,                   name: "tiger4",                   space: 3} };   _.where(obj,{speak:speak}); 

this return:

[objectname: "tiger"space: 7speak: speak()__proto__: object, objectname: "tiger2"space: 1speak: speak()__proto__: object, objectname: "tiger3"space: 3speak: speak()__proto__: object, objectname: "tiger4"space: 3speak: speak()__proto__: object] 

that befuddlement lies. why first method return empty object, second method returns expect...

i aware of question didn't confusion... thank in advance!

that's pretty expected result.

you see, on first example, create new function each object, that:

innerobj1.speak !== innerobj2.speak. function may appear same, it's different object. not speak values different each other, they're different (also new!) function pass value in _.where() function.

on 2nd example, define 1 function , reference each object innerobj1.speak === innerobj2.speak, since speak properties reference same function.

take look: fiddle


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -