javascriptnode.jsobject-initializers

calling an object method from another method not working


Suppose I have the following coding scenario:

export const test = () => {
    return (
        var1,
        var2,
        var3
    ) => {
        return Object.freeze({
            getVarOne: () => var1,
            getVarTwo: () => var2,
            getVarThree: () => var3,
            total: () => var1 + var2 + var3,
            squareTotal: () => Math.pow(total(), 2)
        })
    }
}

let obj1 = test();
let obj2 = obj1(1, 2, 3);
let obj3 = obj2.squareTotal();

What is a way I can access the total method from the squareTotal method? I keep getting undefined for the total method call.


Solution

  • There is an undefined total function called as argument to Math.pow. If you intended to call the member of the object, then you need to specify that, as currently, it is a variable reference, not a property.

    You can use this, but you must make the method a standard function instead of an arrow function -- you can use the ES6 object method notation (omitting the function keyword):

    const test = () => {
        return (
            var1,
            var2,
            var3
        ) => {
            return Object.freeze({
                getVarOne: () => var1,
                getVarTwo: () => var2,
                getVarThree: () => var3,
                total: () => var1 + var2 + var3,
                squareTotal() { return Math.pow(this.total(), 2) }   
            })
        }
    }
    
    let obj1 = test();
    let obj2 = obj1(1, 2, 3);
    let obj3 = obj2.squareTotal();
    
    console.log(obj3);