I am new to JavaScript and was facing this error when I have executed the following code. I have created a class and was trying to use it to create objects from it.
- Computer.js
constructor( // defining the parameters name, modelName, sizeInInches, color, type, generation, clockSpeed, ramSize, diskSize, diskType ) { // defining the properties this.name = name; this.modelName = modelName; this.sizeInInches = sizeInInches; this.color = color; this.type = type; this.processorSpecs = { generation: generation, clockSpeed: clockSpeed, type: type, }; this.ramSize = ramSize; this.diskType = diskType; this.diskSize = diskSize; } // adding the methods here outputConsole() { console.log(this.name, this.ramSize, this.color, this.diskSize); } } export default Computer;
- Script.js
import Computer from "./Computer.js"; const myComp = new Computer( "Pranav's HP Laptop", "HP-envym6-1225dx", 15, "Grey", "Intel i5", "3rd-Generation", "2.2GHz", "8.0 GB", "HDD", "750.0 GB" ); console.log("Output object createdn", myComp); console.log("Output the methodn", myComp.outputConsole()); console.log("Program Finished");
- index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Practice: Making classes and objects</title> <script type="module" src="Computer.js"></script> <script type="module" src="script.js"></script> </head> <body></body> </html>
[This is the output I have obtained][1] [1]: https://i.stack.imgur.com/8afX0.png
Why is the myComp.outputConsole()
being displayed before the "Output the methodn"
in the code console.log("Output the methodn", myComp.outputConsole());
?
Please give me assistance about where i am going wrong. Thanks in advance!! :).
Advertisement
Answer
That happens because your method is calling console.log inside it.
When you call it on this line
console.log("Method output", myComp.outputConsole());
The external console.log must execute myComp.outputConsole() before it executes itself. The text inside the outputConsole method is shown before the text “Method output” because myComp.outputConsole() does not return anything and executes an internal console.log. Once the method is resolved, console.log(“Method output”) is executed.
To obtain the expected result you could simply separate the console logs.
console.log("Method output") myComp.outputConsole(); // this will also be printed because you implemented the internal console.log
Or you can change your method to return a string
outputConsole() { return this.name +""+ this.ramSize +""+ this.color +""+ this.diskSize; }