user3732793 user3732793 - 2 months ago 4
Javascript Question

Use module in Node js and reassign values

I have a javascript module simplified as an eye pose.

var pose = {};
var eye = {};
var left = {};
left.pitchPos = 37;
left.yawPos = 47;

exports.init = function () {
eye.left = left;
pose.eye = eye;
return this;
};

exports.eye = function (e) {
if(typeof(e) !== "undefined"){
pose.eye = e;
}
return pose;
};

exports.pose = pose;


This is how I use it:

var pose = require('./pose').init();
console.log(JSON.stringify(pose));
pose.eye.left = { yawPos: 99, pitchPos: 11 };
console.log(JSON.stringify(pose));


Why do I get the same output twice?

Potentially I have not understood modules and scopes yet, any hint on doc is welcome

Answer

The "problem" is with wrong usage of this keyword in this function:

exports.init = function () { 
    eye.left = left;
    pose.eye = eye;
    return this;
};

Returning this in this context means "return the module itself". This means that your assignment (pose.eye.left = ...) does something like this (in context of pose.js file):

exports.eye.left = ...

exports.eye is a Function, so in result you are assigning a new member to the function eye (this is possible, because JavaScript's Functions are Objects).


A proper assignment (without modifications in pose.js file) would look like this:

pose.pose.eye.left = ...