如何在模块函数中无需传参获取Class属性值
解决方案
首先纠正你代码里的语法错误:export.js中的导出函数必须有名称,否则无法通过import {x}导入,修改后的export.js如下:
export function x() { console.log(this.str); }
接下来提供几种无需每次调用x都传入类实例的解决方法:
方法1:调用时用call绑定上下文
在foo类的构造函数中,通过call将当前实例的this绑定给x,这样x内部的this就指向foo的实例,能直接访问str属性:
import {x} from './export.js'; class foo { constructor() { x.call(this); } str = 'A String'; }
方法2:提前绑定x到实例
如果需要在类的多个方法中调用x,可以在构造函数中将x绑定到实例上,后续直接调用this.x()即可:
import {x} from './export.js'; class foo { constructor() { this.x = x.bind(this); this.x(); // 首次调用 } str = 'A String'; someMethod() { this.x(); // 后续调用无需再次绑定 } }
方法3:将x改为接受上下文参数(可选)
虽然你提到不想每次传参,但如果允许x做微小修改,可以让它接受一个上下文参数,这样在类里调用时直接传this:
// export.js 修改后 export function x(context) { console.log(context.str); } // 类中的调用 import {x} from './export.js'; class foo { constructor() { x(this); } str = 'A String'; }
原代码失败原因
模块默认运行在严格模式下,直接调用x()时,x内部的this值为undefined,因此访问this.str会抛出Cannot read property 'str' of undefined的错误。
内容的提问来源于stack exchange,提问作者Codemaster United
相关产品推荐
相关产品推荐

