未捕获的 TypeError TypeError:this.somePropFun 不是对象中的函数

问题描述 投票:0回答:2

我无法访问作为对象属性值的函数。仅当从另一个属性调用函数时才会发生这种情况。直接调用携带函数的属性就可以了。

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

这给出:

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

这个效果很好:

X.somePropFun("")
DONE

我的猜测是它必须与范围界定有关。

javascript function scope typeerror javascript-objects
2个回答
0
投票
 SomeOtherProp:function(Y){ 
         console.log(typeof this.somePropFun)
        //some processing 
        this.somePropFun("","")
    } 

这解决了它。用常规函数语法替换箭头函数


0
投票

就像对象的方法一样写,不要使用箭头函数,或者使用正则函数表达式

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

或者

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("")
© www.soinside.com 2019 - 2024. All rights reserved.