Uncaught TypeError TypeError: this.somePropFun is not a function in an object

34 Views Asked by At

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

There are 2 best solutions below

0
shadow On
 SomeOtherProp:function(Y){ 
         console.log(typeof this.somePropFun)
        //some processing 
        this.somePropFun("","")
    } 

This solved it . Replace arrow function with regular function syntax

0
Daniel Hakobyan On

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("")