I am developing a NodeJS module and its file size is increasing dramatically, however I have realized that I can divide my module into two separate modules. When this happens only a few functions in my second module need to use internal C++ classes of my first module. Is it possible to somehow only pass the prototype of the first module to the second one?
Example:
Module A:
Has a class called cModuleA:
class cModuleA {
//declarations
data* pointer;
}
Module B:
Has about 100 function but only one of them needs to manipulate data* pointers. It needs to return cModuleA object as well (therefore it needs a prototype of cModuleA or be aware of cModuleA implementation)
I have tried to export symbols from the first module (dllimport/dllexport in windows) but I was just wondering if there is any better option to inject dependencies at C++ level.
I found a solution to this problem and I am going to go over it in detail since probably nobody else has attempted to do such a crazy thing!
Assume you have two native node modules. Meaning that they live in separate executable files (.node). One of them is moduleA and the other one is moduleB:
ModuleA:
class cppClass
{
public:
cppClass();
~cppClass();
// C++ stuff here
}; // !class cppClass
class cppClassWrap
: public node::ObjectWrap
{
public:
// used for initializing this class for Node/v8
static void Initialize(v8::Handle<Object> target);
// internal C++ data accessor
cppClass* GetWrapped() const { return internal_; };
// internal C++ data accessor
void SetWrapped(cppClass* n) { internal_ = n; };
private:
cppClassWrap();
cppClassWrap(cppClass*);
~cppClassWrap() { if (internal_) delete internal_; };
// JS stuff here
static Persistent<Function> constructor;
// JS c'tor
static NAN_METHOD(New);
// internal C++ data
cppClass* internal_;
}; // !class cppClassWrap
//-------------------------------------------------
// JS c'tor implementation
NAN_METHOD(cppClassWrap::New)
{
NanScope();
cppClassWrap* obj;
if (args.Length() == 0)
{
obj = new cppClass();
}
// **** NOTICE THIS! ****
// This is a special case when in JS land we initialize our class like: new cppClassWrap(null)
// It constructs the object with a pointer, pointing to nothing!
else if (args[0]->IsNull())
{
obj = new cppClass(nullptr);
}
else
{
//copy constructor for the JS side
obj = new cppClassWrap(ObjectWrap::Unwrap<cppClassWrap>(args[0]->ToObject())->GetWrapped());
}
obj->Wrap(args.This());
NanReturnValue(args.This());
}
From this point on, all you need to do is to for example have Persistent handle in ModuleB to store a copy of the constructor of ModuleA's class c'tor in it. For example you can have a method called dependencies and call it in JS like:
var cppClassWrap = require("ModuleA.node").cppClassWrap;
var moduleB = require("ModuleB.node").dependencies({
"moduleA" : function() {return new cppClassWrap(null); }
});
And done! you have module injection at C++ level!
Related
I think this has been addressed somewhere, at some point, just for the life of me I can't remember so here's my question:
I'm doing some javascript work that will be loaded into an existing application. This application has crap loads of functions available and hardly any of it is known to me except some that I want to actually use. So lets say that I know for a fact that window.srslyUsefulFunction will be available to me and I don't care much for porting this in to a typescript definition.
So the question is how do I use window.srslyUsefulFunction in my own typescript file without creating a definition for it?
Example:
class MyClass {
public MyMethod (id : string) : void {
// do something
var result = window.srslyUsefulFunction(id);
// do something (with the result)
}
}
You can add the function to the Window interface and then use it in your TypeScript program:
interface Window {
srslyUsefulFunction(id: number): void;
}
class MyClass {
doSomething() {
window.srslyUsefulFunction(1);
}
}
I have simple workaround.
In index.html
function playIntro() {
intro = new lib.intro();
onlinePlayer.contentContainer.addChild(intro);
stage.update();
}
in my Main.ts I call it like that:
private onClick(event): void {
if (window.hasOwnProperty('playIntro')) {
window['playIntro'].call();
}
}
So... if you want to call "blind" js function from global scope, just use window["foo"].call();
Check if the function exists. If it doesn't, declare it:
if(!window.hasOwnProperty('srslyUsefulFunction')
|| typeof window['srslyUsefulFunction'] !== "function"){
window['srslyUsefulFunction'] = function(){
console.log("You're only running a dummy implementation of srslyUsefulFunction here!");
};
}
I am learning how to split my program across several javascript files that can be used in a browser – see my code below. I want to access the private variables and methods in MODULE while inside MODULE.Submodule (or vice versa). The obvious answer is that I should make those variables and methods public in MODULE. Of course, if I make them public, then they are no longer private. When I had all my code in one single file, then the methods inside what is now MODULE.SubModule could access all the private variables. I want to replicate that capability. That is, the private vars and methods in each module remain private to all the modules (or better, to specific modules) and only the public vars and methods from all modules are made public.
I've found several tutorials on how to achieve the splitting, but none seem to address this specific problem – accessing private vars and methods in one module while in another module in the browser.
// in module.js
let MODULE = (function () {
const privateVar = 'foo';
return {
publicVar: 'bar',
// should return foo -> works
publicMethod: function () { return privateVar; };
};
})();
// in module-submodule.js
MODULE = (function (my) {
const privateVar = 'baz';
my.SubModule = {
// should return baz -> works
publicMethod: function () { return privateVar },
// should return foo from parent MODULE -> DOES NOT work
superPublicMethod: function() { return my.privateVar}
}
return my;
})(MODULE || {});
console.log(MODULE.publicMethod()); // return 'foo'
console.log(MODULE.SubModule.publicMethod()); // returns 'baz'
console.log(MODULE.SubModule.superPublicMethod()); // returns 'undefined'
Thus far I've worked only with relatively small projects (and mostly alone), but this time I have to collaborate with other programmers... basically because of that I must plan the structure of the website very carefully for the avoidance of spending hours debugging the code.
At this point I suppose doing that in the following manner. I divide my code in modules and store each module in a separate file inside an object (or a function) with a made-up name (lzheA, lzheB, lzheC etc.) to avoid conflicts whether an object with the same name was used in an another piece of code. When the document is loaded, I declare a variable (an object) that I use as a main namespace of the application. Properties of the object are the modules I defined before.
// file BI.lib.js
var lzheA = {
foo: function() {
},
bar: function() {
},
}
// file BI.init.js
function lzheK() {
BI.loadPage();
}
// file BI.loadPage.js
function lzheC() {
var result = document.getElementById('result');
result.innerHTML = "that worked";
}
// and so on
var lzheA,lzheB,lzheD,lzheE,lzheF,lzheG,lzheH,lzheI,lzheJ;
// doing the following when the document is loaded
var BI = {
lib: lzheA,
menu: lzheB,
loadPage: lzheC,
customScripts: lzheD,
_index: lzheE,
_briefs: lzheF,
_shop: lzheG,
_cases: lzheH,
_blog: lzheI,
_contacts: lzheJ,
init: lzheK,
}
BI.init();
https://jsfiddle.net/vwc2og57/2/
The question... is this way of structuring worth living or did I miss something because of lack of experience? Would the made-up names of the modules confuse you regardless of the fact that each one used only twice - while declaring the variable and assigning it to a property?
I consider the namespaces a good option when you want to modularize applications in Javascript. But I declare them in a different way
var myModule = myModule || {}; // This will allow to use the module in other places, declaring more than one specificComponent in other js file for example
myModule.specificComponent = (function(){
// Private things
var myVar = {};
var init = function() {
// Code
};
return {
init: init // Public Stuff
};
})();
If you want to call the init method, you would call it like this
myModule.specificComponent.init();
With this approach, i guarantee that the module will not be overwritten by another declaration in another place, and also I can declare internal components into my namespaces.
Also, the trick of just exposing what you want inside the return block, will make your component safer and you will be encapsulating your code in a pretty way.
Hope it helps
Hullo! This is my first question!
I am experimenting with the module pattern promoted by Doug Crockford and others. Mostly very happy with it so far, but I am a little unsure about the best way of handling a certain inheritance pattern.
I have it boiled down to a bare bones case using cat and mammal, although my actual intention is to make objects for a tile based game in canvas.
But here is my bare bones 'animals' case using a browser alert:
var ZOO = ZOO || {};
//
ZOO.mammal = function () {
"use strict";
var voice = "squeak.mp3", // default mammal sound
utter = function () {
window.alert(this.voice);
};
//
// public interface
return {
utter: utter,
voice: voice
};
};
//
ZOO.cat = function () {
"use strict";
// hook up ancestor
var thisCat = ZOO.mammal();
thisCat.voice = "miaw.mp3";
return thisCat;
};
//
var felix = ZOO.cat();
felix.utter();
What bothers me about this approach is that I have had to make voice a public property so that cat can modify it.
What I really want is something like 'protected' visibility (from Java, ActionScript etc.), so that cat can modify voice without anyone with access to felix being able to modify it.
Is there a solution?
You can simulate protected visibility (visible to yourself, and child objects) by passing a blank object to your base "class" to serve as the repository for your protected properties. This will allow you to share properties through your inheritance chain, without making them public.
var ZOO = ZOO || {};
ZOO.mammal = function (protectedInfo) {
"use strict";
protectedInfo = protectedInfo || {};
protectedInfo.voice = "squeak.mp3";
// public interface
return {
utter: function () {
alert(protectedInfo.voice);
}
};
};
ZOO.cat = function () {
"use strict";
var protectedInfo = {};
// hook up ancestor
var thisCat = ZOO.mammal(protectedInfo);
protectedInfo.voice = "miaw.mp3";
return thisCat;
};
Here's a live demo
Sidesteping non-answer:
There are some ways to kind of get protected properties in Javascript but they aren't necessarily very idiomatic. If I were you I would first strongly consider either
Using the convention of public properties prefaced with an underscore (ex.: _voice) to denote privacy. Its very simple and is something of a standard among dynamic languages.
Seek an alternate solution without inheritance. Inheritance often complicates and couples stuff to much, hence the old "prefer composition over inheritance" mantra. Javascript has many features, like duck typing and higher order functions, that often let you avoid using inheritance in situations where you would normaly need it in Java
There is a workaround to simulate protected members, where you make public those members for a while, and then you privatise them again. I'm not a big fan of this, but it's a "solution".
I'm just quoting from this SitePoint article:
Adding Protected Members
Splitting a script into multiple modules is a common and convenient
practice. It makes a large codebase much easier to manage, and allows
for bandwidth savings to be made when modules aren’t always required.
But what if we want to share data between different modules? If we
make that data public then we’ll lose the benefits of privacy, but if
we make it private it will only be available to one module. What we
really need are shared private members, and these are known as
protected.
JavaScript doesn’t have protected members as such, but we can
effectively create them by making data temporarily public. To achieve
this, let me first introduce you to two key functions — extend and
privatise — which we’ll define as part of a utility-functions object:
var utils = {
extend : function(root, props) {
for(var key in props) {
if(props.hasOwnProperty(key)) {
root[key] = props[key];
}
} return root;
},
privatise : function(root, prop) {
var data = root[prop];
try { delete root[prop]; } catch(ex) { root[prop] = null; }
return data;
}
};
The extend function simply adds new properties to an object, while the
privatise function copies a property and then deletes the original. We
can use extend in one module to create a public reference to a private
variable, and then use privatise in another module to copy it back to
a private variable and delete the public reference.
So here’s an example of the first module which has two protected
members (including the utils object itself), and one public member. To
keep the code example short, the utility functions are just empty
shells, but they would be identical to the functions I showed you a
moment ago:
var MyModule = (function() {
var myProtectedData = 909;
var utils = {
extend : function(root, props) { },
privatise : function(root, prop) { }
};
this.myPublicData = 42;
return utils.extend(this, { myProtectedData : myProtectedData, utils : utils });
})();
You can see how we’re using a variant of the revealing module pattern,
to return not just the public members, but the protected members as
well. So at this point we have three public members:
MyModule.myProtectedData, MyModule.utils and MyModule.myPublicData.
Now here’s an example of the last module which uses the privatise
function to copy the specified public members back to private
variables, and then delete their public references:
var MyModule = (function() {
var myProtectedData = this.utils.privatise(this, 'myProtectedData');
var utils = this.utils.privatise(this, 'utils');
return this;
}).apply(MyModule);
And once that’s done the protected members are locked inside their
objects, privately available to both the modules, but no longer
available from outside them.
Note that the privatise function relies on having separate arguments
for the object and the property-key, because objects in JavaScript are
passed by reference. So root is a reference to MyModule, and when we
delete a property from it that’s specified by key, we’re deleting that
property from the referenced object.
But if it was like this:
privatise : function(root) {
var data = root;
try { delete root; } catch(ex) { root = null; } return data;
}
And called like this:
var myProtectedData = this.utils.privatise(this.myProtectedData);
Then the public members would not be deleted — the function would
simply delete the reference, not the property it refers to.
The try ... catch construct is also necessary for older IE versions,
in which delete is not supported. In that case we nullify the public
property rather than deleting it, which is obviously not the same, but
has an equivalent end result of negating the member’s public
reference.
Background
I'm building a javascript based application that works differently on mobile and desktop devices. However, except for the DOM manipulation, most code is common between both platforms, so I have structured all files like:
* foo.core.js
* foo.mobile.js
* foo.web.js
And hoping to leverage object oriented techniques to write cleaner code.
Problem:
I have two JavaScript files, with classes
File 1:
function ClassA()
{}
ClassA.prototype.foo = function(){};
GreatGrandChildA.prototype = new GrandChildA(); // this is where the error is
function GreatGrandChildA ()
{}
File 2:
ChildA.prototype = new ClassA();
function ChildA () // ChildA inherits ClassA
{}
GrandChildA.prototype = new ChildA()
function GrandChildA () // GrandChildA inherits ClassA
{}
Normally, in a language like C++, I would forward declare GrandChildA right in File 1. I would like to know how to do it in Javascript
Edit:
If I make a single file containing all four classes - in the same order in which they are loaded, the example works exactly as expected:
http://jsfiddle.net/k2XKL/
Simple logic for unordered js file loading:
File1:
// ClassB: inherite from ClassA
(function ClassB_Builder() {
if(window.ClassB)return; // ClassB is already defined;
if(!window.ClassA) { // ClassA is already not defined;
setTimeout(ClassB_Builder,0); // shedule class building
return;
}
ClassB=function() {
}
ClassB.prototype=new ClassA;
ClassB.prototype.constructor=ClassB; // can be important for inheritance!!!
})();
File2:
// ClassA: base class
(function ClassA_Builder() {
ClassA=function() {
}
})();
// ClassC: inherite from ClassB
(function ClassC_Builder() {
if(window.ClassC)return; // ClassC is already defined;
if(!window.ClassB) { // ClassB is already not defined;
setTimeout(ClassC_Builder,0); // shedule class building
return;
}
ClassC=function() {
}
ClassC.prototype=new ClassB;
ClassC.prototype.constructor=ClassC; // can be important for inheritance!!!
})();
I assume that on your HTML page, you import File 1 and then File 2.
In File 1, you should see exception because "GrandChildA" is undefined. The function declaration is not done because File 2 has not loaded yet.
In File 2, you're being able to do:
ChildA.prototype = new ClassA();
function ChildA () // ChildA inherits ClassA
{}
because the Javacript runtime hoisted your named function "ClassA" before the code executes until ChildA.prototype = new ClassA();
Please read more about function hoisting and should you be doing it in such situation at http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
The most sane way to accomplish what you want, is to make 2 separate versions of your source code. You're going to want to minify, obfuscate your code and merge all the source files anyway, so it would make sense to create a build script (python would be a great language for a simple build script) that you configure to merge mobile specific files into one (plus the files that both versions share) and non-mobile specific files into another file (and shared files also). In addition you could later add automatic obfuscating and gzipping. Then you can serve the appropriate source version to the appropriate client.
As mentioned in the comments, the requested functionality is not possible.
This is not only a technical problem but also an indication that
the application is not structured appropritately - the design should be improved.
Now, there is a kind of a circular dependency that shoul be avoided.
For comparison you mention that you would solve it in C++ by a forward declaration
of the superclass. But this is also not possible. In C++,
in order to declare a subclass you need to include the file with the
declaration of the superclass. And you cannot solve the problem when there are circular dependencies.