skip to Main Content

I am not able to reach a function which is a value of an attribute of an object . This only happens when function is called from another attribute. Calling the attribute carrying the function directly works just fine .

path = require("path")

var combineThesePaths =function combinePaths(basePath, relativePath) {
    // Use path.join to combine paths safely
    const absolutePath = path.join(basePath, relativePath);
    // Use path.resolve to get the absolute path
    console.log("DONE")
    return path.resolve(absolutePath);
}

X= {
    somePropFun: combineThesePaths,
    SomeOtherProp:(Y)=>{ 
         console.log(typeof this.somePropFun)
        //some processing 
        this.somePropFun("","")
    } 
} 
Z= X.SomeOtherProp("")

This gives:

undefined
Uncaught TypeError TypeError: this.somePropFun is not a function

This works just fine:

X.somePropFun("")
DONE

My guess is it has to do something with scoping .

2

Answers


  1. Chosen as BEST ANSWER
     SomeOtherProp:function(Y){ 
             console.log(typeof this.somePropFun)
            //some processing 
            this.somePropFun("","")
        } 
    

    This solved it . Replace arrow function with regular function syntax


  2. Just write it like method of object, do not use arrow function, or use regular function expression

    path = require("path")
    
     var combineThesePaths =function combinePaths(basePath, relativePath) {
         // Use path.join to combine paths safely
         const absolutePath = path.join(basePath, relativePath);
         // Use path.resolve to get the absolute path
         console.log("DONE")
         return path.resolve(absolutePath);
     }
    
     X= {
         somePropFun: combineThesePaths,
         SomeOtherProp(Y){ 
              console.log(typeof this.somePropFun)
             //some processing 
             this.somePropFun("","")
         } 
     } 
     Z= X.SomeOtherProp("")
    

    Or

    var combineThesePaths =function combinePaths(basePath, relativePath) {
        // Use path.join to combine paths safely
        const absolutePath = path.join(basePath, relativePath);
        // Use path.resolve to get the absolute path
        console.log("DONE")
        return path.resolve(absolutePath);
    }
    
    X= {
        somePropFun: combineThesePaths,
        SomeOtherProp: function(Y){ 
             console.log(typeof this.somePropFun)
            //some processing 
            this.somePropFun("","")
        } 
    } 
    Z= X.SomeOtherProp("")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search