对象属性函数调用报错:Uncaught TypeError: this.somePropFun不是函数
对象属性函数调用失败问题解决
你猜的没错,这个问题确实和作用域有关,核心是箭头函数的this指向规则在搞鬼。
问题原因
你在SomeOtherProp里用了箭头函数,箭头函数的this不会绑定到当前的对象X,而是继承自它被定义时的外层作用域(这里是全局作用域)。全局作用域里压根没有somePropFun这个属性,所以this.somePropFun返回undefined,调用自然报错。
而直接调用X.somePropFun("")时,this会自动绑定到调用它的对象X,所以能正常执行函数。
解决方案
方案1:换成普通函数(最推荐)
普通函数作为对象方法调用时,this会自动绑定到调用它的对象(也就是X),这样就能正确访问this.somePropFun:
path = require("path") var combineThesePaths = function combinePaths(basePath, relativePath) { const absolutePath = path.join(basePath, relativePath); console.log("DONE") return path.resolve(absolutePath); } X = { somePropFun: combineThesePaths, // 把箭头函数改成普通函数 SomeOtherProp: function(Y) { console.log(typeof this.somePropFun) this.somePropFun("", "") } } Z = X.SomeOtherProp("")
方案2:直接引用对象X(适合一定要用箭头函数的场景)
如果必须保留箭头函数,可以直接用对象变量名X代替this,因为X在全局作用域可访问:
X = { somePropFun: combineThesePaths, SomeOtherProp: (Y) => { console.log(typeof X.somePropFun) X.somePropFun("", "") } }
注意:这种方式不够灵活,如果后续对象变量名修改,这里也要同步改,不如方案1通用。
方案3:手动绑定this(不推荐,冗余)
可以通过bind给箭头函数绑定X的this,但其实完全没必要,不如直接用普通函数:
X = { somePropFun: combineThesePaths, } // 绑定X作为this X.SomeOtherProp = (Y) => { console.log(typeof this.somePropFun) this.somePropFun("", "") }.bind(X)
内容的提问来源于stack exchange,提问作者shadow
相关产品推荐
相关产品推荐

