I have an object called Category which uses a method to iterate over an array of products (Product) and return an instance which meets the this.name === query condition:
function Category(products){
this.products = products;
this.findProductByName = function(query){
$(this.products).each(function(){
return this.name === query;
}
}
}
My Product (just in case):
function Product(name){
this.name = name;
}
I then create an instance of Category with products:
var $someCategory = new Category(
[
new Product('foo'),
new Product('bar')
]
)`
and when I call:
$someCategory.findProductByName('foo'); // 'undefined'
even though:
...
this.findProductByName = function(query){
$(this.products).each(function(){
console.log(this.name === query); // returns 'true'
}
}
...
What do I do to return an object when this.name === query is met?
$.each()mechanism ignores the returned values (mostly). What is it that you expect it to do?Productinstance when the conditional is met, so that I can search for products within$someCategoryby name. What do you mean by "ignores the returned values"?returnfrom inside the$.each()callback only returns from that function; it doesn't return from yourfindProductByNamefunction.