I have in an external JavasScript (sun.js) file a class like this :
export default class Sun { constructor(){ this.text = 'I'm shining!'; } static testIfShining() { console.log("is the sun shining?"); console.log(this.text); } }
So I’m importing this class in one of my component
import Sun from '../sun.js'
And then I call my function testIfShining()
in my mounted lifecycle :
mounted() { Sun.testIfShining(); }
When I look at my console, I have the message log
is the sun shining? undefined
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
this.text = 'I'm shining!';
in your code
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); } }
edit: Reply to fast. And also use like this :
Could you try this
mounted() { let sun = new Sun(); sun.testIfShining(); }
example: https://jsfiddle.net/y4675twv/2/