0

I am used to cross platform dev. On the C/C++ side it's simple, but I'm stuck with a problem when using javascript. I want to be able to reuse code from my web-service on the client-side. Currently node.js requires me to write my program in a most unpleasant way but I can handle it:

//MyClass.js
function MyClass()
{
    this.test = function(){}
}

module.exports.MyClass = MyClass;
//server.js

var m = new require('MyClass.js').MyClass();
m.test();
//client.js
$.getScript("MyClass.js", function(){
    var m = new MyClass();
    m.test();
});

To that point it is all fine, but I have an issue when I need to load classes from MyClass.js. How can I make it work across all the platforms? Is there a way to achieve reusability without processing the files?

1

1 Answer 1

2

Node requires you to do nothing. If you aren't a fan of the way the Node module system works, simply don't use it.

//MyClass.js
MyClass = function ()
{
    this.test = function(){}
}

//server.js
require('./MyClass.js');
var m = new MyClass();
m.test();

Now your application is compatible with what you have going on client-side. Just bear in mind that you are now creating classes in the global namespace, which is one reason for using Node's module layout.

I suggest also looking into some of the ways to use a Node-style require on the client. There are many scripts available, such as RequireJS or Browserify.

Sign up to request clarification or add additional context in comments.

7 Comments

On my side with node.js v0.8.15 it doesn't work: src/server.js:3 var m = new MyClass(); ^ ReferenceError: MyClass is not defined which version of node.js are you using?
Sorry, try MyClass = function () { instead of function MyClass().
@icktoofay, Modules don't get their own global scope. Global is global to the entire application. nodejs.org/api/globals.html#globals_global I see what you're getting at though. Let me check my code again and see why this works for me.
@icktoofay, I just tested, and it works fine. However, there may be a path issue... code was missing the ./. editing now.
@icktoofay, No worries, but I am a bit confused myself now! It was my understanding that function something was equivalent to something = function. Any thoughts on that?
|

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.