Problems with fn.call () within a method in a Javascript object

1

I have a problem with fn.call () within a method in an object. I have an arrangement that internally has objects, the values of these objects are type and gender.

    const gustos = [
    {tipo:'libros', genero: 'futuristas'},
    {tipo:'musica', genero: 'rap'}
]

class User{
    constructor(name){
        this.name = name
    }
    listarGustos(arr){
        length = arr.length
        console.log(arr)
        for(let i = 0; i <length; i++){    
        return function (i){
             console.log('${this.tipo} : ${this.genero}')
             console.log(i)
         }.call(arr[i])
        }
    }
}
const victor = new User("victor")

victor.listarGustos(gustos)

to make the sentence of victor.listarGustos (tastes) is only returning me 'books: futurists' that is only the first value of the array is returning me likes. Any correction that I have to make to my code? thanks in advance

    
asked by Victor Lozada 26.05.2018 в 18:04
source

2 answers

1

Already solved.

const gustos = [
    {tipo:'libros', genero: 'futuristas'},
    {tipo:'musica', genero: 'rap'}
]

class User{
    constructor(name){
        this.name = name
    }
    listarGustos(arr){
        length = arr.length
        const print = function(i){
            console.log('#${i + 1 } ${this.tipo} : ${this.genero}')
        }
        // const print = (i) => console.log('#${i + 1 } ${this.tipo} : ${this.genero}')
        for(let i = 0; i < length; i++){
            print.call(arr[i], i)
        }
    }
}
const victor = new User("victor")

victor.listarGustos(gustos)
    
answered by 26.05.2018 / 20:56
source
0

Think that as soon as you type return, the for loop and the current function will close immediately. You can use an IIFE (Feature Expression invoked immediately) and adjust your return function part in the following way that could achieve what you are trying to do:

listarGustos(arr) {
		length = arr.length;
		for (let i = 0; i < length; i++) {
			(function(i) {
				return function() {
					console.log('${this.tipo} : ${this.genero}');
				}.call(arr[i]);
			})(i);
		}
	}
    
answered by 26.05.2018 в 21:02