How to document JavaScript objects (from UML perspective) - javascript

I am wondering (perhaps more so from a UML point of view) how others have managed to document JavaScript objects successfully.
JavaScript can be expressed as OOP but in addition to these objects, files may also contain 'lose standing' scripts, which belongs to the file itself - not the object you defined.
Would you document the file itself as a class, and the classes it contain as nested classes?

Someone adapted UML for web artifact, its called the "WAE" extension of UML.
If you work with node.js, i created a module that generate class diagram for javascript/node/html/css. Its called wavi. For javascript, function,variable are automatically recognized. You can use it for documenting your application.
https://www.npmjs.org/package/wavi

No, it wouldn't make sense to document a JavaScript file as a class (with inner classes), but the "classes" it contains may be documented with a UML class diagram. However, since there is no explicit class concept in JavaScript, people use different code patterns for defining a "class". The most commonly used code pattern is the constructor-based definition of classes as proposed on the Mozilla website. In this approach, the constructor function (say, C) represents the class. It defines a number of properties (using this) and a number of methods/functions (using C.prototype). Then, in a UML class diagram, these properties and methods can be described in the form of a class rectangle.

If you want to document your javascript objects, you can even use a MVC pattern for javascript projects. I would personally try to avoid using innerclasses and use proper relationships between classes. If you mean with innerclasses; putting multiple classes sepperated in the same js file, then; yes that's a valid option. Javascript doesn't care in which file a class is, it only thinks about the classes (unlike Java if I'm correct).
Example I wrote 8 years ago for school showing the Control class:
function Control()
{
var myView = new View(respondOnChoice);
var myMathTest = new MathTest();
var myExercise = new Exercise();
function respondOnMathTestChoice()
{
myView.emptyMainDiv();
myView.showNameAndClassChoice();
}
}
Start.js (to initiate the control):
if (window.attachEvent) //IE
{
window.attachEvent("onload", initApp);
}
if (window.addEventListener)//Firefox
{
window.addEventListener("load", initApp,false);
}
function initGame()
{
var myControl = new Control();
}
In my opinion, this is the best way to use OOP in javascript. If you program properly, you won't have to mind about anything to do with innerclasses, just relationships between classes.

Related

Creating library without encapsulation Javascript

I am very new in creation of libraries in javascript and encapsulations in javascript. I created very first library with the help of one or two tutorials from the web.
The example looks like the following,
<script>
var libs=[];
(function(libs){
function firstLibrary (){
this.initializeHoldings = function () {}
  this.myLibrary = function(){
    var _myLibraryObject = [{FirstName: 'Ibrahim', LastName: 'Shaikh', CompanyName: 'Plexitech'},
{FirstName: 'Nizam', LastName: 'Siddiqui', CompanyName: 'Neoquant'}];
    return _myLibraryObject;
  }
}
libs.customLibrary = firstLibrary;
})(libs);
let $ = new libs.customLibrary();
console.log($.myLibrary());
</script>
This is how my code looks,
now the confusions are,
1): What are the difference between libraries and encapsulations in
javascript?
2): How can I create library without encapsulating it in javascript?
3): Does encapsulation always create library?
Yes, I know it might be a silly question for some of you but many newbies might get confused on this.
1): What are the difference between libraries and encapsulations in javascript?
A "library" is a set of functions/classes. "Encapsulation" doesn't really have a meaning as a unit of code like "library." Wikipedia's short definitions of "encapsulation" are pretty good:
A language mechanism for restricting direct access to some of the object's components.
A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.
As you can see, neither means anything like "library." But you would probably use encapsulation in parts of your library.
2): How can I create library without encapsulating it in javascript?
Probably, if you didn't have any data maintained by the library that you needed to prevent other code from using, and didn't need to combine data with methods.
3): Does encapsulation always create library?
No, not at all. They're largely unrelated terms and concepts.

j2v8: creating new instance of binded object

Our teams is currently under consideration of which JavaScript Engine Bridge to use. We are choosing between LiquidCore and J2V8.
My question is concerning j2v8. Supposedly, I have to create several instances of some java class in JavaScript, how can one achieve this in j2v8 using standard instantiation annotation (new ClassName())? In liquidcore you can bind some class, that extends JSFuction, with super constructor:
JSFunction(JSContext ctx, final String methodName, final Class<?extends JSObject> instanceClass)
and register property with desired class name like this:
jsBaseContext.getJsContext().property("WebSocket", this);
and then on calling:
var x = new WebSocket();
java method methodName will fire, where we'll get new instanceClass as JSValue object as parameter, already binded and ready to use in javascript.
Since no one is going to discuss this topic, i'll answer myself.
This feature is not currently considered to be added in official J2V8 release, however there is a branch on Mizumi's pull request. So, have a look, if you've faced similar issues.

Connecting Javascript properties to Java object

The Problem
I am trying to feed a Java object into a script that would normally operate on the Document Object Model (DOM) of a web page. For the most part this functions as intended. However I have encountered a problem when dealing with attributes/properties of the DOM elements.
A particular property chain of interest is somediv.firstChild.href. What I can't figure out is how to get the firstChild property value dynamically. The simplest way I can think of at the moment is to use source.replaceAll("firstChild", "firstChild()"); to force the firstChild property to invoke the function firstChild() instead. However this will eventually open up a new can of worms.
The Question
How do I define an object that can be passed to a javascript function that can be operated on via the DOM?
Background
Learnings from C#
Before diving into Java I had learnt C#. In C# the concept of setters and getters is quite prevalent. If this interface method were available in Java my problem would be solved.
public string firstChild {
get { return this.getFirstChild(); }
set { this.setFirstChild(value); }
}
Current Implementation
The script is currently invoked by wrapping it in a function where I can pass in the window and document Java objects into the function's workspace.
document is a special top-level version of SpoofedDomElement (that extends it) but is functionally identical to the sample shown below. window is another object with minimal functions that handle event listeners.
Javascript (snippet) to operate on DOM
var somediv = document.createElement('div');
somediv.style.display = "block"
somediv.innerHTML="<a href='/mywork/server/test.html'>The Test Server Homepage</a>";
var linkvalue = somediv.firstChild.href;
This snippet is stored as the string theOriginalSource and used in the next section.
Java code to evaluate Javascript
String wrappedSource = "var scriptToInvoke = function(window, document){"
+ "\n" + theOriginalSource // from above
+ "\n};"
Object result = invocable.invokeFunction("scriptToInvoke", window, document);
This snippet wraps the javascript snippet so that I can pass in objects to use as window and document.
Java classes that spoof DOM elements
public class SpoofedDomElement {
public SpoofedDomElement firstChild;
public String id;
public String innerHtml;
public String href;
public SpoofedStyleProperties style = new SpoofedStyleProperties();
public String tagname;
...
}
public class SpoofedStyleProperties {
public String background = "transparent none repeat scroll 0% 0% auto padding-box border-box";
public String color = null;
public String display = "inline";
}
The above classes handle irrelevant parts of the code just fine (such as the assignment somediv.style.display = "block"). But it starts to fall apart when handling the values of firstChild or innerHtml when either value is changed.
Past Work
N.B. I include this section in all my questions to document what I have tried for future SO users who get here by Google. This might help someone reach a solution by aiding brainstorming.
Attempted Solutions
I have attempted to use a framework (HtmlUnit) to evaluate the Javascript. But I couldn't control which Javascript snippets were executed.
Potential Solutions
The following are questions that I am currently researching to find a solution. If I find anything I will report back.
Is there a way to emulate C# getter/setter behaviour in Java?
Can Javascript evaluate firstChild as a function?
Is there a way to create a wrapper within Javascript with getter/setters that can invoke my Java class's functions?
Is there an Apache Commons library for Nashorn (or similar) that isn't as heavy as the complete simulation frameworks (such as Selenium)?
It appears that you're trying to implement friendly access of script objects from Java code as well as trying to provide script-friendly API on top of java library/libraries.
For the first part [ script object access from Java ]
Apart from javax.script.Invocable interface, you can use JSObject. Nashorn exposes script objects as instances of jdk.nashorn.api.scripting.JSObject/.ScriptObjectMirror
https://docs.oracle.com/javase/8/docs/jdk/api/nashorn/jdk/nashorn/api/scripting/ScriptObjectMirror.html
For the second part [ friendlier access of Java objects from scripts ]
You can write script friendly wrappers in script itself using "JSAdapter".
Doc and Example:
https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-JSAdapterconstructor
If you'd prefer to do in Java, you can implement your own jdk.nashorn.api.scripting.JSObject/.AbstractJSObject.
Doc and Example:
https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-jsobject
Other nashorn specific script extensions may also be used to trap unknown property/method access in per object basis:
noSuchProperty hook in any script object:
https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-noSuchProperty
noSuchMethod hook in any script object:
https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-noSuchMethod
Object.bindProperties:
There script API extension can be used to bind properties of one object to another - the source object could be a Java object as well.
https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-Object.bindProperties
With jdk9, there is more flexible inter-language linking possible with Dynalink API [ http://openjdk.java.net/jeps/276 ]
See also:
https://blogs.oracle.com/sundararajan/entry/dynamic_linker_api_for_the
https://blogs.oracle.com/sundararajan/entry/writing_pluggable_dynalink_linker_and
https://blogs.oracle.com/sundararajan/entry/nashorn_javascript_access_to_python
There are dynalink samples "samples/dynalink" directory of Nashorn OpenJDK repository:
http://hg.openjdk.java.net/jdk9/dev/nashorn/file/4a6ee1185fc8/samples/dynalink

oop javascript deepcopy mixins multiple inheritance

First of all Hello to everyone, and sorry for my English.
I would still take advantage of the expertise and availability of this community.
In this period I'm studying inheritance in javascript, Crockford patterns, deepcopy shallowCopy etc.
I have also read many post in stakoverflow(here,here ecc..) but i dont hide that my my doubts are still many.
My aim was to create a kind of pseudo-multiple inheritance without using jquery or methods as objectCreate.
Pseudo because, as i have learned from reading various post, multiple inheritance in javascript does not exist.
In my script there are two "superClasses" (HomoErectus an HomoSapiens) an a "subClass" (ModernMan).
My copyProtoDeep function copies all properties of the prototypes of the superclasses in the prototype of the subClass.
This function takes an indefinite number of parameters the first will be the class that inherits from other classes specified in the function call.
To avoid shallowcopy if copyProtoDeep finds an object or an array the function clone this elements.
That said, I would like, if is possible, some answers to the following questions.
Is my code correct?
Is this type of ineritance a mixin?
Which are the negative aspects (or drawbacks) of this procedure?
The use of uber is correct?
Can i improve my code?
I understand that my questions are perhaps too many for a single post, but also a partial response will be read with pleasure.
Thanks to all in advance
<script type="text/javascript">
function copyProtoDeep() {
var len = arguments.length;
arguments[0].prototype.uber=[]
for (j = 1; j <len; j++) {
var parent = arguments[j].prototype;
var child = arguments[0].prototype;
for (var i in parent) {
if (parent.hasOwnProperty(i)) {
if (typeof parent[i] === 'object') {
child[i] = Array.isArray(parent[i]) ? parent[i].slice(0) : JSON.parse(JSON.stringify(parent[i]));
} else {
child[i] = parent[i];
}
}
}
child.uber[j] = arguments[j].prototype
}
}
function HomoErectus(name){
this.name=name
this.sayHello=function(){return 'Hello from '+this.name}
}
HomoErectus.prototype.discovery='fire'
HomoErectus.prototype.scream='yabadabadoo'
HomoErectus.prototype.friends=['wilma','Betty','Barney']
HomoErectus.prototype.uberTest1=function(){
if(this.uber){return 'the ancestor of '+this.name+" discovered "+this.uber[1].discovery}
else{return this.name+' discovered '+this.discovery}
}
function HomoSapiens(name){
this.name=name
this.iam=function(){return 'I am an Homosapiens an my name is '+this.name+' and my weapons are '+this.dangerousWeapons.w1}
}
HomoSapiens.prototype.discovery='wheel'
HomoSapiens.prototype.dangerousWeapons={w1:'bow and arrows',w2:'Spear and shield'}
HomoSapiens.prototype.uberTest2=function(){if(this.uber){return 'yes yes'}else{return 'no no'}}
function ModernMan(){
HomoErectus.apply(this, arguments);
HomoSapiens.apply(this, arguments);
}
copyProtoDeep(ModernMan, HomoErectus,HomoSapiens)
ModernMan.prototype.discovery='pc'
var fred=new HomoErectus('Fred')
console.log(fred.uberTest1())
var bubba=new HomoSapiens('Bubba')
console.log(bubba.uberTest2())
var john = new ModernMan('John')
john.friends.push('Riky')
john.dangerousWeapons.w3='guns and bombs'
console.log(john.uber[1].friends)
console.log(john.uber[2].dangerousWeapons)
console.log(john.uberTest1())
console.log(john.uberTest2())
</script>
there are my answers:
Is my code correct?
I think the mixin has no exact rules, so your code is probably right. I didn't find any bigger problem.
Is this type of ineritance a mixin?
If you inherit all methods, then the mixin is (can be) equal to multiple inheritance. And because you also called super constructor, it looks more like inheritance than mixin.
Which are the negative aspects (or drawbacks) of this procedure?
The diamond problem. You probably heard about it. Its a common problem of multiple inheritance. If HomoSapiens and HomoErectus will have same method, then according to your mixin last argument of your copyProtoDeep wins, so HomoSapiens method will be used. But it is the thing about mixins... with inheritance, it is known problem and inheritance isnt supposed to solve it. On the other side, every solution from mixin is acceptable. So if you define that last argument method will have a priority, then it is a correct solution.
The use of uber is correct?
I see one problem. What if parent is also a mixin? Then it has parent.prototype.uber, which will overwrite child.prototype.uber.
Can i improve my code?
I would try to fix the previous problem with uber. For example watch ecma-262 5.1 specification of Property Attributes. This is good thing for libs or patterns. With it you can implement uber different way, so it can't be overwritten for example.
Last words
I have to say that Im not a mixin or multiple inheritance expert. I avoid it. Im just good in javascript and rather use simple inheritance and interfaces. So this was just my point of view.

Compound Javascript Elements

I've got this page I'm doing some tests in Javascript and jQuery: JS Tests
I've got a few questions on how to create, not sure if this is right term, but compound controls via Javascript. In something like Flash, you'd create the Object class, have the getters and setters, draw your images, etc. In JS, it seems to be a very different thought process. My main question is How do you create multiple elements with getters and setters to be rendered, filtered, and interacted with in Javascript?
The main code regarding this example sits with:
var html = (function(){
// var FRAG = $(document.createDocumentFragment());
htmlBox = $(document.createElement("div"));
var eTitle = $(document.createElement("h4"));
var ePrice = $(document.createElement("p"));
// set class first
htmlBox.addClass("box")
htmlBox.css({
backgroundColor : color
})
// set text values
eTitle.text(title);
ePrice.text("$" + price);
htmlBox.append(eTitle)
htmlBox.append(ePrice)
return htmlBox;
})();
... inside the Box() class. If someone could take a look at the source and let me know what isn't quite right, that'd be great.
EDIT
Here's the final result for this example. Some logistics to work out, but what I'm after.
http://geerswitch.in/tests/obj/
As for the jQuery creating nodes, the built in JS version works fine for this, and some research on Google shows that the non-jquery way is faster in most cases anyway (and looks worse, imo)
You're doing it almost right. You've created a Box class to represent your higher-order UI element, you're instantiating it for each element, and your main program is manipulating the elements through its interface. The only thing you're missing is the split between the public interface and the private implementation. There's nothing to prevent me from doing myBox.price += 10 right now, even though the Box interface clearly implies that price should be set at construction and never modified.
JavaScript doesn't have visibility modifiers like "private" and "public", but you can create the same effect yourself. Check out Douglas Crockford's explanation for the details. Crockford is an opinionated genius when it comes to JavaScript, and he's the brains behind JSLint and JSON.

Categories

Resources