[英]Why does data in my JavaScript class is undefined when calling it from a component?
我在外部 JavasScript (sun.js) 文件中有一个 class,如下所示:
export default class Sun {
constructor(){
this.text = 'I\'m shining!';
}
static testIfShining() {
console.log("is the sun shining?");
console.log(this.text);
}
}
所以我在我的一个组件中导入这个 class
import Sun from '../sun.js'
然后我在已安装的生命周期中调用 function testIfShining()
:
mounted() {
Sun.testIfShining();
}
当我查看我的控制台时,我有消息日志
is the sun shining?
undefined
function 正在工作,但我有一个未定义的数据this.text
值
如何在构造函数中重用该值? 我希望我的数据像属性一样工作,这样我就可以在我的 class 中的每个 function 中重复使用它。
如果你在这里很好地编写/复制你的代码,你必须转义单引号。 喜欢
this.text = 'I\'m shining!';
在你的代码中
export default class Sun {
constructor(){
this.text = "I'm shining!"; // <------- Use also double quote
}
testIfShining() { // <------ remove the static
console.log("is the sun shining?");
console.log(this.text);
}
}
编辑:快速回复。 也可以这样使用:
你能试试这个吗
mounted() {
let sun = new Sun();
sun.testIfShining();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.