Convert Actionscript to Javascript - javascript

I was just wondering is there anyway to convert Actionscript to Javascript. When I say Actionscript I mean Actionscript 3. I've used google swiffy but Actionscript 3 is hardly supported. I've also heard of Jangaroo but its not what I want. Even if its a code comparison! Thanks!

Javascript and ActionScript (especially AS3) are syntactically similar languages and both are based on the ECMAScript Specification. There are some small differences in the actual code such as:
//Actionscript:
var a:String = new PlayerName();
//JavaScript:
var a = new PlayerName();
This is a demonstration that JavaScript does not have explicit variable type declarations, but this is not the real problem.
What you're asking goes much further than syntactic incompatibilities, as JS and AS work with completely different APIs. ActionScript has stages, frames and other Flash-based things which do not exist in JavaScript's environment. JavaScript - usually running in a browser - is used to manipulate documents, DOM nodes and CSS properties.
This means that unless you're just doing simple function calls and mathematics (without any dependency on the user or their environment) the things your program is doing simply cannot be transferred to another environment. For example, you cannot tell JavaScript to play() or goToAndStop() because there are no frames to play, stop or go to in a HTML document.
Unfortunately, I think what you're wondering is valid, but the question is almost certainly incorrect. If you have an application created in Flash or any other AS-enabled environment, you probably want to think about porting or re-writing it to the new context.

You might have a look at Falcon JS: https://github.com/apache/flex-falcon

http://www.gotoandlearn.com/play.php?id=172
Just check it out the above. It might be useful.

Related

Javascript: Where getter/setter values are stored? [duplicate]

I was thinking about this today and I realized I don't have a clear picture here.
Here are some statements I think to be true (please correct me if I'm wrong):
the DOM is a collection of interfaces specified by W3C.
when parsing HTML source code, the browser creates a DOM tree which has nodes that implement DOM interfaces.
the ECMAScript spec has no reference of browser host objects (DOM, BOM, HTML5 APIs etc.).
how the DOM is actually implemented depends on browser internals and is probably different among most of them.
modern JS interpreters use JIT to improve the code performance and translate it to bytecode
I am curious about what happens behind the scenes when I call document.getElementById('foo'). Does the call get delegated to browser native code by the interpreter or does the browser have JS implementations of all host objects? Do you know about any optimizations they do in regard to this?
I read this overview of browser internals but it didn't mention anything about this. I will look through the Chrome and FF source when I have time, but I thought about asking here first. :)
All of your bullet points are correct, except:
modern JS interpreters use JIT to improve the code performance and translate it to bytecode
should be "...and translate it to native code". SpiderMonkey (the JS engine in Firefox) worked as a bytecode interpreter for a long time before the current JS speed arms race.
On Mozilla's JS-to-DOM bridge:
The host objects are typically implemented in C++, though there is an experiment underway to implement DOM in JS. So when a web page calls document.getElementById('foo'), the actual work of retrieving the element by its ID is done in a C++ method, as hsivonen noted.
The specific way the underlying C++ implementation gets called depends on the API and also changed over time (note that I'm not involved in the development, so might be wrong about some details, here's a blog post by jst, who was actually involved in creating much of this code):
At the lowest level every JS engine provides APIs to define host objects. For example, the browser can call JS_DefineFunctions (as demonstrated in the SpiderMonkey User Guide) to let the engine know that whenever script calls a function with the specified name, a provided C callback should be called. Same for other aspects of the host objects (e.g. enumeration, property getters/setters, etc.)
For the core ECMAScript functionality and in some tricky DOM cases the JS engine/the browser uses these APIs directly to define host objects and their behaviors, but it requires a lot of common boilerplate code for e.g. checking parameter types, converting them to the appropriate C++ types, error handling etc.
For reasons I won't go into, let's say historically, Mozilla made heavy use of XPCOM for many of its objects, including much of the DOM. One feature of XPCOM is its binding to JS called XPConnect. Among other things, XPConnect can take an interface definition in IDL (such as nsIDOMDocument; or more precisely its compiled representation), expose an object with the specified properties to the script, and later, when a script calls getElementById, perform the necessary parameter checks/conversions and route the call directly to a C++ method (nsDocument::GetElementById(const nsAString& aId, nsIDOMElement** aReturn))
The way XPConnect worked was quite inefficient: it registered generic functions as callbacks to be executed when a script accesses a host object, and these generic functions figured out what they needed to do in every particular case dynamically. This post about quickstubs walks you through one example.
"Quick stubs" mentioned in the previous link is a way to optimize JS->C++ calls time by trading some code size for it: instead of always using generic C++ functions that know how to make any kind of call, the specialized code is automatically generated at the Firefox build time for a pre-defined list of "hot" calls.
Later on the JIT (tracemonkey at that time) was taught to generate the code calling C++ methods as part of the native code generated for "hot" paths in JS. I'm not sure how the newer JITs (jaegermonkey) work in this regard.
With "paris bindings" the objects are exposed to webpage JS without any reliance on XPConnect, instead generating all the necessary glue JSClass code based on WebIDL (instead of XPCOM-era IDL). See also posts by developers who worked on this: jst and khuey. Also see How is the web-exposed DOM implemented?
I'm fuzzy on details of the three last points in particular, so take it with a grain of salt.
The most recent improvements are listed as dependencies of bug 622298, but I don't follow them closely.
JS calls to DOM methods like getElementById cause the JS engine to call into the C++ code that implements the DOM. For example, in Firefox, the call ends up in nsDocument::GetElementById(const nsAString& aId, nsIDOMElement** aReturn).
As you can see, Firefox maintains a hashtable that maps ids to elements in C++ as an optimization in this case, so it doesn't walk the whole DOM tree looking for the id.
The DOM is implemented as a language-independent library pretty much in all major browser implementations, which means it's in a different library from the Javascript engine. For example in IE, the JS engine is implemented in jscript.dll while the DOM is implemented in mshtml.dll. Safari has Nitro(JS) and WebCore(DOM). Chrome has V8(JS) and WebCore(DOM), and Firefox has SpiderMonkey/TraceMonkey(JS) and Gecko(DOM).
What this means is that anytime your JS has to access the DOM, it has to reach over to the DOM library - which is inherently slow because of all the marshaling that has to take place. An analogy that has been used is 2 pieces of land connected by a toll bridge, any time you touch the DOM, you must cross over the bridge and cross back - paying a performance toll.
References
Video: Building High Performance Web Applications and Sites
Book: High Performance Javascript (Chapter 3 on the DOM)

JavaScript inline functions like in C++

Is there any ability in future ECMAScript standards and/or any grunt/gulp modules to make an inline functions (or inline ordinary function calls in certain places) in JavaScript like in C++?
Here an example of simple method than makes dot product of vectors
Vector.dot = function (u, v) {
return u.x * v.x + u.y * v.y + u.z * v.z;
};
Every time when I'am writing somethink like
Vector.dot(v1, v2)
I want be sure that javascript just do this calculations inline rather then make function call
Given that the OP asks for performance, I will try to provide an answer.
If you are optimizing for the V8 engine, you can check the following article to see which functions are inlined, and how deoptimization affects your code.
http://floitsch.blogspot.com/2012/03/optimizing-for-v8-inlining.html
For example, if you want to see if Vector.dot is inlined, use the following command line where script.js contains both your definition and calling code:
d8 --trace-inlining script.js
The optimization algorithm differs from engine to engine, but the inlining concept should be pretty much the same. If you want to know about other engines, please modify the question to including the exact engine in order to get some insights from JS engine experts.
Modern JS engines already inline functions when they identify that it is possible and useful to do that.
See http://ariya.ofilabs.com/2013/04/automatic-inlining-in-javascript-engines.html. Quote:
If you always worry about manual function inlining, this is a good time to revisit that thought. Simply write the code to be readable even if it means breaking the code into multiple small functions! In many cases, we can trust the modern JavaScript engines to automatically inline those functions.
I suppose you could write a pre-processor to handle inline keywords and do the necessary source code rewriting (and then wire it into gulp or grunt if you insist), but that would seem to be quite complex, and frankly most likely not worth the trouble.

Learning how JavaScript optimizes execution, if at all

Is there a way to learn at how JavaScript is interpreted and executed? In .NET or JAVA for instance, you could look at the generated byte code, in C you could look at the generated assembly instruction but from what I gather, JavaScript is interpreted line by line and then it varies on the JS engine in different browsers.
Still is there a way to learn how JavaScript does this? Does the interpreter in modern browsers tend to look ahead and optimize as a compiler might?
For instance, if I did:
$('#div1').css('background-color','red');
$('#div1').css('color','white');
Could I have a perf gain by doing:
var x = $('#div1');
x.css('background-color','red');
x.css('color','white');
The point of this question is to get some information how one might gain some insight as to how JavaScript is run in the browser.
The optimization steps taken, as always, depend on the compiler. I know that SpiderMonkey is fairly well documented, open source, and I believe does JIT compilation. You can use it outside of the browser to tinker with, so that's one less black-box to deal with when experimenting. I'm not sure if there's any way to dump the compiled code as it runs to see how it optimizes in your code, but since there's no standard concept of an intermediate representation of Javascript (like there is with .NET/Java bytecode) it would be specific to the engine anyway.
EDIT: With some more research, it does seem that you can get SpiderMonkey to dump its bytecode. Note, however that optimizations can take place both in the interpreter that generates the bytecode and the JIT compiler that consumes/compiles/executes the bytecode, so you are only halfway there to understanding any optimizations that may occur (as is true with Java and .NET bytecodes).
V8 does some amazing things internally. It compiles to machine code and creates hidden classes for your objects. Mind-blowing details here: https://developers.google.com/v8/design
Ofcourse when it comes to the DOM, performing lookups can only go that fast. Which is why chaining or temp variables can make a difference, especially in loops and during animations.
Besides that, using the right selectors can be helpful. #id lookups are undoubtedly the fastest. Simple tagname or class lookups are reasonably fast as well. jQuery selectors like :not can't fall back on builtins and are considerably slower.
Besides reducing lookups, another good rule of thumb with the DOM is: If you need to do a lot of DOM manipulation, take out some parent node, do the manipulations, and reinsert it. This could save a whole lot of reflows/repaints.
Yes, you will get a performance gain. The DOM is not queried twice, and only one jQuery object is instantiated.
Yet you should not do this for performance (the gain will be negligible), but for code quality. Also, you do not need a variable, jQuery supports chaining:
$('#div1').css('background-color','red').css('color','white');
and the .css method also can take an object:
$('#div1').css({'background-color': 'red', 'color': 'white'});

Is Jquery *compiler* possible?

When I saw this question I thought it would be helpful if a jQuery compiler could be written. Now, by compiler, I mean something that takes in jQuery code and outputs raw javascript code that is ultimately executed.
This is how I vision a block of jQuery code execution:
a jQuery function is called and parameters are passed to it
the function calls a raw javascript function and passes the parameters it received to it
the newly called function performs the intended action
I understand that this is a very simplified model and it could be much more complex, but I think the complexity is reduced to steps 2 and 3 being repeated with different raw js functions being called and each time fed with all or a subset of parameters / previous results.
If we subscribe to that model, then we might come up with methods to make the jQuery functions perform double-duty:
What they already do
Logging what they did in form of raw_function(passed_params)
Am I making some wrong assumptions that would make this impossible?
Any ideas how Firebug's profiler attempts to get function names? Could it be used here?
Edit
What I was thinking was making a black box with input / output as:
normal jquery code → [BB] → code you'd write if you used no library
I called this a compiler, because you compiled once and then would use the resulting code.
I argued that it could have at least educational use, and probably other uses as well.
People said this would take in a small amount of code and output a huge mass; that does not defy the intended purpose as far as I see
People said I'd be adding an extra, needless step to page rendering, which, given only the resulting code would ultimately be used (and probably be used just for studying), is not correct.
People said there is no one-to-one relation between javascript functions and jquery functions, and implied such a converter would be too complicated and probably not worth the effort. With this I now agree.
Thank you all!
I think what you mean is: if you write
var myId = $("#myId")
it will be converted to
var myId = document.getElementById("myId")
I think its possible, but the problem is, jQuery functions return jQuery objects, so in the above example, the first myId will be a jQuery object & the second will be a node object(i think) which will affect other functions that needs to use it later in the code after compilation. Especially if they are chained
secondly you will have to be sure that the conversion actually has performance benefits.
However if you are aware of all this and you can plan you code accordingly, i think it will be possible
If the purpose of the compiler to convert Javascript (which may be jquery or anything) to better Javascript (which I understood from you saying "ultimately executed"), then Google has already done that. They made closure compiler and some have tried it with JQuery in this post. Isn't this what you are suggesting ?
jQuery code is "raw JavaScript code" so I'm not sure what a compiler would really buy you. That's like writing a C# compiler which takes C# 4.0 code and emits C# 1.1 code. What's the benefit?
jQuery isn't a different language which replaces or even sits on top of JavaScript. It's a framework of JavaScript code which provides lots of useful helpers for common tasks. In my view, it's greatest benefit is that its distinctive structure helps to differentiate it from the more "Java-like" languages.
JavaScript by itself is deceptively similar to other languages and this tends to be one of its biggest faults as a language. People try to think of it in terms of Java, even though the similarities pretty much stop at the name. Structurally, JavaScript is very different in many ways (typing, scope, concurrence, inheritance, polymorphism, etc.) and I particularly like how jQuery and other modern JavaScript projects have brought the language to stand on its own merits.
I guess to get back to the question... If you're looking to turn jQuery-style JavaScript into Java-style JavaScript, then that's something of a step backwards. Both versions would be interpreted by the browser the same way, but one of the versions is less elegant and represents the language more poorly than the other.
Note that jQuery isn't the only framework that does these things, it's just the most popular. Would such a compiler need to also handle all the other frameworks? They all do different things in different ways to take advantage of the language. I don't think that homogenizing them to a "simpler" form buys us anything.
Edit: (In response to the various comments around this question and its answers, kind of...
How would you structure this compiler? Given that (as we've tried to point out) jQuery is JavaScript and is just a library of JavaScript code, and given how browsers and JavaScript work, your "compiler" would just have to be another JavaScript library. So essentially, what you want is to go from:
A web page
The jQuery library
Some JavaScript code which uses the jQuery library
to:
A web page
The jQuery library
Some JavaScript code which uses the jQuery library
Your "compiler" library
Some more JavaScript code which sends the previous JavaScript code through your library somehow
Your "jQuery-equivalent" library
Some more JavaScript code which replaces the original JavaScript code with your new version
in order to make things simpler? Or to somehow make debugging tools like FireBug easier to use? What you're proposing is called an "obfuscator" and its sole purpose is to make code more difficult to reverse-engineer. A side effect is that it also make code more difficult to understand and maintain.
Now, by compiler, I mean something
that takes in jQuery code and outputs
raw javascript code that is ultimately
executed.
I think that statement may indicate what's going wrong for you.
jQuery is a library implemented in the Javascript language. jQuery isn't a language separated from Javascript. jQuery is a collection of Javascript code that you can use to make Javascript development easier. It's all Javascript. A "jQuery compiler" to convert "jQuery code" to "raw Javascript" would be quite useless because jQuery is raw Javascript.
What you probably actually want is a Javascript compiler. In that case, it's certainly possible. In fact, some web browsers nowadays actually "compile" on the Javascript code in some kind of bytecode to enhance performance. But development workflows involving Javascript typically don't involve a compiler tool of some kind.
Apparently what you actually want is to "inline" jQuery code into your code, sort of like this:
var myfoo = $('#foo'); → var myfoo = document.getElementById('foo');
This is actually something a C++ compiler would do to optimize performance, but Javascript is not C++ so it doesn't apply here.
I don't see how this is useful. The point of jQuery is to simplify Javascript development by providing a consistent interface like the $() function. By performing this "inlining" procedure you produce code that is even harder to read and maintain.
And why add an extra step? Why not just deliver the application javascript code and the jQuery library to the browser? Why add an extra step involving an extra tool to convert Javascript to Javascript that doesn't provide any substantial extra benefits?

Why am I finding Javascript/jQuery so difficult to get right?

My background is in C and I've picked up PHP, mySQL, HTML, CSS without too much issue.
But I'm finding Javascript/jQuery surprisingly difficult to get right.
Very frustrating.
Why?
It seems to violate a number of traditional programming principles (e.g. variable scope)
Undefined variables seem to appear out of nowhere and already have values associated with them. For example (from the jQuery docs):
$("a").click(function(event) {
event.preventDefault();
$('<div/>')
.append('default ' + event.type + ' prevented')
.appendTo('#log');
});
What exactly is "event"? Do I have to use this variable name? Should I just assume that this object is magically instantiated with the right stuff and I can use any of the methods list at the JQuery API?
There seems to be bunch of random rules (e.g. return false to stop a default action, but sometimes this doesn't work?)
Non-deterministic behavior when debugging. (e.g. I refresh the browser, try something and get result X for JS variables I'm watching in Firebug. I refresh again and I get result Y?)
Very messy looking code that is hard to follow. What happens when? I'm using Firebug and Chrome Developer Tools, but I'm not getting enough visibility.
It seems like everyday there's some random JS "rule" that comes up that I've never seen before in any of my JS books or tutorials.
What do I need to do to make Javascript/jQuery more deterministic, controlled, and logical to me?
Are there any resources that explain Javascript's quirks/gotchas?
Thanks!
1) It seems to violate a number of traditional programming principles (e.g. variable scope)
You need to declare variables using var, else it will go into the global scope.
2) Undefined variables seem to appear out of nowhere and already have values associated with them (how did this happen?)
This is possibly related to 1) and/or 4).
3) There seems to be bunch of random rules (e.g. return false to stop a default action, but sometimes this doesn't work?)
You need to let the handler return false as well. E.g. form onsubmit="return functionname()". You also need to return from the "main" function, not only from a closure (a function inside a function), referring to your previous question. It would only return into the "main" function and continue on.
4) Non-deterministic behavior when debugging. (e.g. I refresh the browser, try something and get result X for JS variables I'm watching in Firebug. I refresh again and I get result Y?)
Probably the code was executed before the HTML DOM was finished populating. You need to hook on window.onload or $(document).ready() whenever you want to execute stuff during page load.
5) Very messy looking code that is hard to follow. What happens when? I'm using Firebug and Chrome Developer Tools, but I'm not getting enough visibility.
I bet that you're talking about jQuery source? It's just a large library. You should after all not worry about this when debugging. Rather worry about your own code. However, make sure that you're looking at the unminified version of jQuery's source code.
See also:
JavaScript: the bad parts
What should every JavaScript programmer know
Douglas Crockford's "Javascript: The Good Parts" was an invaluable resource. Javascript plays a lot more like Lua, Lisp, or Python than C, it just happens to LOOK like C.
Link provided to Amazon; I snagged mine from O'Reilly.
To be honest, I think you have a good understanding. Some of my hangups were similar. The way that I have been moving on is "well, if that's the way it is, then that's the way it is". Just accept the idiosyncrasies and plow forward. PHP does some of the same things (variables can show up out of nowhere, etc...). Just code the way you want to code and if it works, then great!
Then after you get to that point start breaking out the profiler and see if there's anything that you can optimize.
Here are a couple of things:
If you understand CSS, then jQuery selectors should be easy. As far as the code goes, that's straightforward too if you can deal with chaining and JSON. EDIT: also, the jQuery documentation on everything is EXCELLENT! And There is no shortage of jQuery experts here on SO to help us noobs (and hopefully we can return the favor for newer noobs).
There is a scope to work with. (Basically) anything written outside of a function or object is in global scope. If you are inside of an object or function and use var then that sets the variable's scope
Javascript isn't like a C-based language (C++ or PHP even). It uses prototypes to deal with class/object relationships rather than a subclassing scheme.
The #1 thing that threw me for a loop is that any JS that appears anywhere on the page or that was included in <script> tags is fair game. If you have a global variable in one script, you can use that same variable in a completely different script and it will work. That may be what you mean about variables showing up out of nowhere. Also, there are some DOM based variables that can just "show up" too.
Anyways, I think that if you just plow ahead, you'll get some "AHA" moments. I'm a relative noob to programming, but I continually grow as long as I don't hang up on something that doesn't have too much of an impact on actually making the code run.
It's a language based on prototypal inheritance and is influenced by functional programming languages and the paradigm so it isn't completely just OO/Procedural like other languages. Variables are implied globals unless declared with var.
Please include an example?
return false exits out of the function as with any language's return statement. preventDefault() would be the DOM method to cancel the default behaviour of a link
Javascript is used primarily on the client side. Since there are many user agents, each of them have a different implementation of the DOM, which is very inconsistent, moreso than JS itself. Again, please include a real example to get a definitive answer.
You'll find messy looking code in any language, and maybe your lack of understanding perceives the code as messy, when in fact it isn't so bad. Or maybe you're looking at some minified/obfuscated code.
I recommend http://eloquentjavascript.net/ for learning aspects of Javascript.
Things you'll learn from the link above
lambdas
closures
Prototypal inheritance
Event based programming
Debugging
DOM
"JavaScript: The Good Parts" by Douglas Crockford is a good start
In your case, the appendices ("the bad parts" and "the awful parts") might be the most interesting :)
Crockford's "Javascript: The Good Parts" gives some common JS patterns that help with variable privatization and scoping. This is for javascript in general. For jQuery I just use the API. Also the Yui Theatre videos on javascript are quite good
Javascript can be a little tricky and some of it's functional aspects confuses people. If you actually learn and understand the language you'll find it really useful, most people just randomly start using it and then just hate.
Read javascript the good parts by crockford, it's really helpful: http://javascript.crockford.com/
Also make sure you understand closure. It's a fundamental that people don't get but often use.
In terms of variable scope, there are local and global variables. One of the gotchyas of variable scope can be seen in this example:
var thisIsAGlobalVariable
function anon () {
var thisIsALocalVariable
thisIsAGlobalVariable = 5; //if you don't use the var prefix inside a fn, it becomes global
}
You are finding it difficult because:
javascript has another kind of syntax.
javascript is dificult to debug
javascript has no autocompletion like c# etc) ?or does it
javascript has illogical rules (they become logical once you are known with them)
everything can be done in 1000 ways, and when you search for a solution, you will find 2000 answers :) where c#, php mostly have a good practice function u "should/could" use
However, I started using js/jquery a half year ago, with the same reasoning as you do, and I stuck to it, and now I use it daily to enhance my webapps.
I just love it (especcially jquery). It is a life saver, I know what and where to look, I can do about anything with it.
Everything seems logical.
If I can give you one advice: javascript/jquery is a sour apple, but just hang in there, bit trough and you won't regret it.
also, a loooot of people use it and are always willing to lend a hand if needed (I know I do)
Javascript is tricky. You don't have a compiler watching your back. To compensate, unit testing becomes more important. I've been doing my unit testing with jQuery/QUnit, but I recently started using Jasmine (http://github.com/pivotal/jasmine) and I recommend it 200%. Its a great testing framework.
If you're not familiar with testing, or testing with javascript, I'd highly recommend finding unit tests for other OSS javascript projects (hopefully for code you could use) and seeing how they test it.
With unit tests, you'll make the same mistakes, but catch them much sooner and with less grief. And if your tests are good, the mistakes won't come back after you fix tham.
I don't know how much UI design you have done in C, but the event variable only shows up when it is sent by the caller and the handler needs to, well, handle the object. If you do reading on event object, the confusion in q #2 should go away.
There is no event handling in PHP, so I think you have not came across this issue in the past. JavaScript is a programming language with its own purpose, so it was designed to work for that specific purpose.
Maybe you have to link your code to an HTML onclick="event()" button to fire off as the event.

Categories

Resources