0

I am new in node. I'm trying to access object properties and methods with .notation and it is giving undefined error for object properties and "TypeError: dice.roll is not a function " for object functions.

Here is code:

object file:

var dice = {
    size: 4,
    count:3,    
    roll:function(){
        var result = Math.ceil(this.size * Math.random());
        return result;
    } 
};
exports.diceObjectName = dice;

program file:

var dice = require("./dice");    
console.log(dice);    
console.log(dice.roll());
2
  • What is the result of console.log(dice) ? Commented Jan 15, 2018 at 13:23
  • Try to change exports.diceObjectName = dice; into exports.dice = dice;. Commented Jan 15, 2018 at 13:25

3 Answers 3

1

You need to use module.exports = dice

var dice = {
    size: 4,
    count:3,    
    roll:function(){
        var result = Math.ceil(this.size * Math.random());
        return result;
    } 
};

module.exports = dice;
Sign up to request clarification or add additional context in comments.

Comments

0

You are exporting your object inside diceObjectName. So in order to use it you have to do so:

var dice = require("./dice").diceObjectName;

Example

Comments

0

Instead of this code: exports.diceObjectName = dice; try this: module.exports = dice

or this:

var dice = require("./dice").diceObjectName;    
console.log(dice);    
console.log(dice.roll());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.