LilacEilim
LilacEilim

Reputation: 89

return this returns undefined

I have a helper method called magnitude that I tried to use chaining functions with it.

That is my magnitude.js:

export const Magnitude = props => {
   let data;

    const formatterObj = {
        getData: props => {
            return data ? data : { ...props, magnitude: '', negativeSign: '', format: '' };
        },
        setData: newData => {
            data = { ...data, ...newData };
        },
        format: str => {
            const { value } = data;
            const absValue = Number(Math.abs(value));
            const negativeSign = value > 0 ? '' : '-';
             const magnitude = (absValue) => { return {value: absValue/10, abbr: 'k'}};

            formatterObj.setData({ value: magnitude.value, magnitude: magnitude.abbr, negativeSign, format: str });
            return this;
         }
    };

    data = formatterObj.getData(props);

    return formatterObj;
};

and this is my app.js:

 console.log(Magnitude({value: 10000,currency: "$"}).format('NSVU'));

I can see on the webkit tool when I debug it that on the return this it is actually return the entire obj including the method format. But when I console.log it prints undefined.

Upvotes: 0

Views: 97

Answers (1)

Jack Bashford
Jack Bashford

Reputation: 44087

You need to use parentheses if you wish to return an object from an arrow function.

const magnitude = absValue => ({ value: absValue / 10, abbr: "k" });

Also, if you wish to return this property from format, you have to use a normal (ES5-style) function - otherwise the this you want is lost due to the lexical binding of the arrow function.

format: function(str) {...}

Upvotes: 2

Related Questions