jeudi 16 juillet 2020

Patter design and Map function in Javascript. What dosen't work?

What is the difference between the fisrt code and the second? The fisrt work, but the second does not work, this return a array with number 4 and not a array object with corners = 4. The problem is in the map function.

Fist code

   const Strategy = {
            map : function(array){
                    const newArray = array.map((e) => { e.setCorners(4);  return e });
                    return newArray
                },
        }


    const objectCorners = function(corners){
    
        _corners = corners
    
    
    
        return ({
            corners : _corners
            getCorners : (() => { return corners}),
            setCorners : ((corners) => {_corners = corners}),
        })
    }
const array = [new objectCorners(3),new objectCorners(6),new objectCorners(7)]
const result = Strategy["map"](array)
console.log(result) // [{corners : 4},{corners : 4},{corners : 4}]

Second Code

 const Strategy = {
            map : function(array){
                    const newArray = array.map((e) => {return e.setCorners(4); });
                    return newArray
                },
        }


    const objectCorners = function(corners){
    
        _corners = corners
    
    
    
        return ({
            corners : _corners
            getCorners : (() => { return corners}),
            setCorners : ((corners) => {_corners = corners}),
        })
    }
const array = [new objectCorners(3),new objectCorners(6),new objectCorners(7)]
const result = Strategy["map"](array)
console.log(result) // [4,4,4]

Aucun commentaire:

Enregistrer un commentaire