I have in an external JavasScript (sun.js) file a class like this :
JavaScript
x
11
11
1
export default class Sun {
2
constructor(){
3
this.text = 'I'm shining!';
4
}
5
6
static testIfShining() {
7
console.log("is the sun shining?");
8
console.log(this.text);
9
}
10
}
11
So I’m importing this class in one of my component
JavaScript
1
2
1
import Sun from '../sun.js'
2
And then I call my function testIfShining()
in my mounted lifecycle :
JavaScript
1
4
1
mounted() {
2
Sun.testIfShining();
3
}
4
When I look at my console, I have the message log
JavaScript
1
3
1
is the sun shining?
2
undefined
3
The function is working but I have an undefined value for the data this.text
How can I reuse the value inside my constructor? I want to my data works like attribute so I can reuse it in every function in my class.
Advertisement
Answer
If you write/copy your code well here you have to escape the single quote. Like
JavaScript
1
2
1
this.text = 'I'm shining!';
2
in your code
JavaScript
1
12
12
1
export default class Sun {
2
constructor(){
3
this.text = "I'm shining!"; // <------- Use also double quote
4
}
5
6
testIfShining() { // <------ remove the static
7
console.log("is the sun shining?");
8
console.log(this.text);
9
}
10
}
11
12
edit: Reply to fast. And also use like this :
Could you try this
JavaScript
1
6
1
mounted() {
2
let sun = new Sun();
3
sun.testIfShining();
4
}
5
6
example: https://jsfiddle.net/y4675twv/2/