Reputation: 890
Trying to complete a simple node.js exercise, I have tried several variations on this. I suspect I am missing something very simple.
The reason I created var Calc was because I wanted to export the 'calculator' function.
the error:
/Users/alex/zdev/react-project/calc.js:4
var add = function(){
^^^
SyntaxError: Unexpected identifier
file calc.js: (file has been shortened to stay concise)
var readline = require('readline-sync');
var Calc = {
var add = function(){
var num1 = readline.question("num1: ");
var num2 = readline.question("num2: ");
console.log(num1 + num2);
};
}
module.export = Calc;
calling file:
var calc = require('./calc');
var Calc = new calc.Calc();
Calc.add();
Calc.sub();
Calc.divide();
Upvotes: 0
Views: 1688
Reputation: 890
solution is as follows:
call file:
var calc = require('./calc');
var Calc = calc.Calc;
Calc.add();
calc file:
var Calc = {
add: function(){
var num1 = readline.question("num1: ");
var num2 = readline.question("num2: ");
console.log(num1 + num2);
},
divide: function(){
var num1 = readline.question("num1: ");
var num2 = readline.question("num2: ");
console.log(num1 / num2);
},
sub: function(){
var num1 = readline.question("num1: ");
var num2 = readline.question("num2: ");
console.log(num1 - num2);
}
}
module.exports = {Calc:Calc}
the following lines pulled are where the original mistakes were:
defining my class after importing from other function
Calc = calc.Calc;
using a commas to seperate my object properties instead of a semicolon
},
not defining a dictionary in module exports. Also, I wrote 'module.export' not 'module.exports' originally
module.exports = {Calc:Calc}
And I forgot to put my parseInt() for my num1 and num2 values.
Upvotes: 0
Reputation: 6211
I suggest using JavaScript classes introduced in ECMAScript 2015
class Calculator {
constructor() {
console.log("[Calc] created!");
}
static add(a, b) {
return a+b;
}
}
let Calc = new Calculator();
Upvotes: 0
Reputation: 642
If you want to make constructor function (I mean from your syntax) you should do it like this:
function Calc() {
}
Calc.prototype.add = function() {
var num1 = readline.question("num1: ");
var num2 = readline.question("num2: ");
console.log(num1 + num2);
};
module.exports = Calc;
and then you import this like:
var Calc = require('./calc');
var calc = new Calc();
calc.add();
calc.sub();
calc.divide();
But I prefer for you to use ES6 class syntax, and the Calc constructor function will look like:
class Calc {
constructor() {}
add() {
var num1 = readline.question("num1: ");
var num2 = readline.question("num2: ");
console.log(num1 + num2);
}
}
module.exports = Calc;
Upvotes: 0
Reputation: 19617
You define a new object Calc
with a function add
, but the syntax is incorrect. The correct syntax is:
var Calc = {
add: function() {
var num1 = readline.question("num1: ");
var num2 = readline.question("num2: ");
console.log(num1 + num2);
}
};
Upvotes: 2