I know both languages are from the same ECMA-262 standard. It seems that the two are becoming very similar with JavaScript adding event listeners for core Object instances through methods like freeze and seal in EMCAScript-262 5th edition and such. I was wondering what the differences are?
First of all ActionScript 3 and JavaScript are both defined in ECMA-262 so they have a lot in common. Both languages feature prototype inheritance for instance. It is however not correct that ActionScript fully implements ES4.
ActionScript implements a couple of features that are not defined in ECMA-262 and some -- but definitely not all -- of ES4.
So what does AS3 add to ECMA-262? Those are also the differences to JavaScript:
Dynamically and statically typed code
Packages, Classes and Interfaces
Standard OO inheritance model (not prototype based, statically typed)
uint and int datatype
E4X (ECMA-357)
Type-safe conditional compilation (ES4)
Vector.<T> datatype (ES4)
Maybe I have forgotten some features. I am not sure if XML, XMLList etc. are already defined in 262 or came with 357.
The key difference however is the standard library. JavaScript comes with a couple of predefined classes like DOMElement and browser dependent additions. ActionScript has a fairly large standard library with features like video streaming and is consistent over all platforms.
I've been programming in both ActionScript and Javascript, and from a less-technical standpoint, I see two main differences.
1) JavaScript is more powerful. You are allowed to do much more with the language because it does not have a "compiler" or types. There are some great frameworks out there like ExtJS and jQuery that try and simplify things for you, but even with them, you are really allowed to do an amazing amount of damage if you want to.
2) ActionScript is much more confining and hence, much easier to maintain. Adobe did a lot of work to keep you out of the difficult parts of ECMAScript. ECMAScript Objects, prototypal inheritance, and closures are three concepts that you really don't need to understand to program in ActionScript. You just need to understand how to use Adobe's "Class" object.
For simple uses, I prefer JavaScript. However, once the project gets large, it depends who you are coding for. If I had a team of 5 developers programming at a scrappy start-up, I'd choose JavaScript in a heartbeat. However, in the girth of a large corporation, or academia, you might be safer relying on Adobe's platform.
Hope that helps.
One is type Safetly. Actionscript requires that you set a type for all objects, and JavaScript doesn't (for that matter, in JavaScript, one variable may be one type and then immediately set to another type).
Actionscript is object oriented. Although you can sort of have this in JavaScript, Actionscript allows for object inheritance, etc.
Essentially the main difference I find is that ActionScript is more a verbose statically-typed class-based language where as javascript is a prototypal language.
Unfortunately there is no type-inference in ActionScript so using Flex Builder gives a warning every time you leave something untyped which I find unnecessary and overly verbose, not only does it make it more verbose than javascript but I find equivalent code to be more verbose than C#.
However the extra verbosity does have yield perf improvements and extra type safety at compile-time. Unfortunately this also adds to build time quite significantly, in Java Script apps of any size I'm used to instant feedback whereas my last ActionScript project had build time exceeding 2 minutes.
From a developer point of view, what matter most:
1) Javascript is not really OOP, it has NO super keyword, which means if you override( by any means ) something, you can't call it through super, and this is the deal breaker for complex programs for which OOP is the key, and Actionscript3 is all OOP, you can have millions line of Actionscript3 code working together, and well maintained.
2) Actionscript3 runs in Flash Player which has only one implementation from Adobe, this means it's consistent all the time, all browsers( as long as installed Flash Player), but Javascript runs in browsers directly, but each browser has its own implementation, which means your Javascript code has to be tested against all targeted browsers to ensure working.
The key differences are that ActionScript 3 supports both class-based inheritance and prototypal inheritance, enforces namespace bindings between class names and file names, and does not support some global JavaScript methods such as eval. Fortunately, you can do several things to bridge the gap.
You can globally set the namespace using ES for ECMAScript or AS3 for ActionScript 3:
use namespace ES;
use namespace AS3;
If you are using the AS3 namespace, any method override must use the AS3 namespace
and the override attribute.
If you are not using the AS3 namespace, you can use the prototype methods and propertyIsEnumerable.
You can selectively use the AS3 namespace version of a property or method in a dynamic function:
var nums:Array = new Array(1, 2, 3);
nums.AS3::pop();
trace(nums); // output: 1,2
To turn off class based inheritance, you can also use the following compiler options:
compc -as3=false -strict=false -es=true
import *
class foo
{
dynamic function foo()
{
}
}
If you do not use the AS3 namespace, an instance of a core class inherits
the properties and methods defined on the prototype object.
If you decide to use the AS3 namespace, an instance of a core class inherits the
properties and methods defined in the class definition.
Here is a common features between ECMAScript-4 and ECMAScript-2017 or later:
Feature ES4/ES6+ ES4 Only
Rest parameter ☑
Destructuring ☑
ByteArrays ☑
Class ☑
Interface ☑
Static fields ☑
Parameter default ☑
Rest Parameters ☑
Bound methods ☑
dynamic this value ☑
multiple catch clauses ☑
short-circuit-and (&&=) ☑
short-circuit-or (||=) ☑
Type Annotations ☑
References
Simulating AS3 language features in JavaScript using AMD and ES5
JavaScript 2 Draft
ECMAScript 4th Edition[proposed]:Predefined Types and Objects
The New Browser War
ECMAScript 1-on-1
The Trouble with JavaScript: JavaScript has no Class
What's New in ECMAScript-4
David Flanagan on JavaScript 2
JavaScript 2 and the Future of the Web
Writing Classes
Faster byte array operations with ASC2
Managing event listeners
frankly it's not the same, cuz action script is loaded with EMQJ24, the new language for high development website. while JS still with it EMCA22, the difference between those are the style and format of the code. and also action script are ages enough, that's why most of programmer nowdays using CSX01 updated language from cSS,it can recognize all type off language without any line.
Related
I would like to get to know if there are classes in JavaScript ECMAScript 5? I read some literature and there are different opinions about it. I know that it is possible to emulate classes, but I am not sure if they are called classes. Do you maybe also have some proofs?
Are these classes simply pseudo classes or what is the correct term for it?
JavaScript/ECMAScript is a prototype-based programming language.
Wikipedia’s definition of this is:
Prototype-based programming is a style of object-oriented programming in which behaviour reuse (known as inheritance) is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as prototypal, prototype-oriented, classless, or instance-based programming.
Well, know it is your decision whether to call them classes.
But some people in the JS world call them classes and with ECMAScript 6 there will be a keyword to create such prototypes, called class. (Which implies that these prototypes should be called class.)
Since you are writing a paper, you could take a definition of class (there are a few out there), mention which you used and whether that is applicable in JavaScript. (If that somehow belongs to your work.)
Some definitions of class are also summarized in a great book by John C. Mitchell. (Mitchell, John: Concepts in Programming Languages. Cambridge University Press, 2003.)
On classes in Simula he writes: (p. 326)
Class: A Simula class is a procedure that returns a pointer to its activation record. The body of a class may initialize the object it creates.
On classes in Smalltalk he writes: (p. 327)
Class: A Smalltalk class defines class variables, class methods, and the instance methods that are shared by all objects of the class. At run time, the class data structure contains pointers to an instance variable temple, a method dictionary, and the superclass.
He also states that the concept of classes in Java and C++ is very similar to the concept in Smalltalk, which was a OO pioneer.
We can see that class can be defined differently, but both definitions above don’t seem to quite match JavaScript prototypes.
"class" is a term for many things. The classes you are looking for are a concept, and are certainly used in JavaScript. We implement the concept by reification, which is easily possible with JavaScripts powerful, object-oriented prototype inheritance. This model is quite different from the object model used in other programming languages, where classes are more a compiler artifact than concrete objects.
That the concept is implemented by means of generic language features allows for multiple slightly different implementations (some of which even don't rely on prototypes). So when the term "class" is used, we don't know how exactly it would look like. Only if we refer to a specific class with an implementation, it's clear what structure is meant (assuming your familiar with the kind of implementation).
There is however a quite standard pattern (implementation) with a constructor function that is invoked with new to create instances, and a prototype object that is used for sharing methods. The pattern also defines how to setup inheritance and subclassing.
You're right that there is no syntactical class structure in ES5 (though the keyword is reserved, and implemented in ES6 by the standard structure).
From MDN:
Classes are syntax sugar over constructor functions
You can use this new construction in ES5 by using some compiler:
Babel
Traceur
JSX
TypeScript
Objects in JavaScript can be used as Hashtable
(the key must be String)
Is it perform well as Hashtable the data structure?
I mean , does it implemented as Hashtable behind the scene?
Update: (1) I changed HashMap to hashtable (2) I guess most of the browser implement it the same, if not why not? is there any requirement how to implement it in the ECMAScript specs?
Update 2 : I understand, I just wonder how V8 and the Firefox JS VM implements the Object.properties getters/setters?
V8 doesn't implement Object properties access as hashtable, it actually implement it in a better way (performance wise)
So how does it work? "V8 does not use dynamic lookup to access properties. Instead, V8 dynamically creates hidden classes behind the scenes" - that make the access to properties almost as fast as accessing properties of C++ objects.
Why? because in fixed class each property can be found on a specific fixed offset location..
So in general accessing property of an object in V8 is faster than Hashtable..
I'm not sure how it works on other VMs
More info can be found here: https://v8.dev/blog/fast-properties
You can also read more regarding Hashtable in JS here:(my blog) http://simplenotions.wordpress.com/2011/07/05/javascript-hashtable/
"I guess most of the browser implement it the same, if not why not? is there any requirement how to implement it in the ECMAScript specs?"
I am no expert, but I can't think of any reason why a language spec would detail exactly how its features must be implemented internally. Such a constraint would have absolutely no purpose, since it does not impact the functioning of the language in any way other than performance.
In fact, this is absolutely correct, and is in fact the implementation-independence of the ECMA-262 spec is specifically described in section 8.6.2 of the spec:
"The descriptions in these tables indicate their behaviour for native
ECMAScript objects, unless stated otherwise in this document for particular kinds of native ECMAScript objects. Host objects may support these internal properties with any implementation-dependent behaviour as long as it is consistent with the specific host object restrictions stated in this document"
"Host objects may implement these internal methods in any manner unless specified otherwise;"
The word "hash" appears nowhere in the entire ECMA-262 specification.
(original, continued)
The implementations of JavaScript in, say, Internet Explorer 6.0 and Google Chrome's V8 have almost nothing in common, but (more or less) both conform to the same spec.
If you want to know how a specific JavaScript interpreter does something, you should research that engine specifically.
Hashtables are an efficient way to create cross references. They are not the only way. Some engines may optimize the storage for small sets (for which the overhead of a hashtable may be less efficient) for example.
At the end of the day, all you need to know is, they work. There may be faster ways to create lookup tables of large sets, using ajax, or even in memory. For example see the interesting discussion on this post from John Reseig's blog about using a trie data structure.
But that's neither here nor there. Your choice of whether to use this, or native JS objects, should not be driven by information about how JS implements objects. It should be driven only by performance comparison: how does each method scale. This is information you will get by doing performance tests, not by just knowing something about the JS engine implementation.
Most modern JS engines use pretty similar technique to speed up the object property access. The technique is based on so called hidden classes, or shapes. It's important to understand how this optimization works to write efficient JS code.
JS object looks like a dictionary, so why not use one to store the properties? Hash table has O(1) access complexity, it looks like a good solution. Actually, first JS engines have implemented objects this way. But in static typed languages, like C++ or Java a class instance property access is lightning fast. In such languages a class instance is just a segment of memory, end every property has its own constant offset, so to get the property value we just need to take the instance pointer and add the offset to it. In other words, in compile time an expression like this point.x is just replaced by its address in memory.
May be we can implement some similar technique in JS? But how? Let's look at a simple JS function:
function getX(point) {
return point.x;
}
How to get the point.x value? The first problem here is that we don't have a class (or shape) which describes the point. But we can calculate one, that is what modern JS engines do. Most of JS objects at runtime have a shape which is bound to the object. The shape describes properties of the object and where these properties values are stored. It's very similar to how a class definition describes the class in C++ or Java. It's a pretty big question, how the Shape of an object is calculated, I won't describe it here. I recommend this article which contains a great explanation of the shapes in general, and this post which explains how the things are implemented in V8. The most important thing you should know about the shapes is that all objects with the same properties which are added in the same order will have the same shape. There are few exceptions, for example if an object has a lot of properties which are frequently changed, or if you delete some of the object properties using delete operator, the object will be switched into dictionary mode and won't have a shape.
Now, let's imagine that the point object has an array of property values, and we have a shape attached to it, which describes where the x value in this property array is stored. But there is another problem - we can pass any object to the function, it's not even necessary that the object has the x property. This problem is solved by the technique called Inline caching. It's pretty simple, when getX() is executed the first time, it remembers the shape of the point and the result of the x lookup. When the function is called second time, it compares the shape of the point with the previous one. If the shape matches no lookup is required, we can take the previous lookup result.
The primary takeaway is that all objects which describe the same thing should have the same shape, i.e. they should have the same set of properties which are added in the same order. It also explains why it's better to always initialize object properties, even if they are undefined by default, here is a great explanation of the problem.
Relative resources:
JavaScript engine fundamentals: Shapes and Inline Caches and a YouTube video
A tour of V8: object representation
Fast properties in V8
JavaScript Engines Hidden Classes (and Why You Should Keep Them in Mind)
Should I put default values of attributes on the prototype to save space?
this article explains how they are implemented in V8, the engine used by Node.js and most versions of Google Chrome
https://v8.dev/blog/fast-properties
apparently the "tactic" can change over time, depending on the number of properties, going from an array of named values to a dictionary.
v8 also takes the type into account, a number or string will not be treated in the same way as an object (or function, a type of object)
if i understand this correctly a property access frequently, for example in a loop, will be cached.
v8 optimises code on the fly by observing what its actually doing, and how often
v8 will identify the objects with the same set of named properties, added in the same order (like a class constructor would do, or a repetitive bit of JSON, and handle them in the same way.
see the article for more details, then apply at google for a job :)
I'm currently designing some API that will eventually be used in GWT, and I'm wondering if the number of methods in a Java class affects the size of an individual Object instance in JavaScript, after compiling the Java code using GWT.
Expressed another way, if I have an abstract base class with say 200 methods, and then sub-classes that override 2 of those, will the "cost" (memory usage) of those 200 methods be paid once for the application, or once per subclass instance?
In Java, the number of methods does not affect the Object size, but I don't know how this works in JavaScript.
The "200" number comes from trying to work-around the lack of Reflection in GWT, but I'd still be interested in the answer even if there was a way to get "fake reflection".
For this kind of question, there will not be an answer on Stackoverflow that beats your own experiments:
Write a class with 200 methods, then write one that subclasses it and overrides 2 methods. Compare JS code sizes to get a basic idea (though this is not the same as instance sizes). Use the Compile Report to get a better understanding. Then try compiling with style PRETTY or DETAILED, open the result in an editor, and verify if the generated code reuses methods or not. (Maybe also try it in OBFUSCATED mode to be sure).
Or, instantiate lots of objects, and inspect memory usage (several browsers offer tools, e.g. https://developers.google.com/chrome-developer-tools/docs/javascript-memory-profiling)
Generally, make sure that your methods do get called at all - otherwise, the compiler will optimize them away.
I've recently been playing with the awesome tool from google that does some code-optimization and partial execution, for instance it would take something like:
//Just an alias for an elementByID selector
function $(bar){
return document.getElementById(bar);
}
//Call the selector
alert($("foo").value);
And shorten it into alert(document.getElementById("foo").value);, which is fairly awesome from an optimization viewpoint.
I'm only explaining this because I would have thought this concept works for larger libraries such as jQuery, which basically attempts to abstract away a bunch of things JavaScript does, like select by IDs.
In a quick test, I loaded the whole jQuery production file up to the compiler and appended a single bit of text at the end of it: alert($("#foo").val());
And quite tragically, the compiler wasn't able to map through jQuery's design and result with the simple example I had above, but rather my output is about 85kb of text with alert($("#foo").K()); stuck on the end. Basically, I just have minified code, and didn't take advantage of the awesome feature demonstrated above.
So my question is, if I do end up using a library, how can I code in such a way that closure compiler is able to simplify my code to it's native JS (or something more effective than 85kb of unused code)? Alternatively, what design should someone take if they wanted to make a small library that plays nice?
AFAIK, jQuery is not (yet) written to be optimized by the Closure Compiler's Advanced Mode. It has an "externs" file which will enable its public properties and classes not to be renamed, but it does not enable most of the optimizations (e.g. dead code removal) as you've discovered. Which is quite a pity, because the jQuery object, if property written, does lends itself quite readily and nicely to the Closure Compiler's prototype virtualization feature.
Slightly off-topic
If you are not tied to jQuery, you may consider the Dojo Toolkit, which can be modified to be used with the Closure Compiler while enabling most optimizations (especially dead-code removal).
See this document for details.
jQuery takes special pains to minify itself and in the process makes itself opaque to the Closure Compiler.
Closure Library is an example of a library that is written to make good use of the Closure Compiler.
Generally, the compiler does best with prototype inheritance and simple structures:
/** #constructor */
function Class () {}
Class.prototype.f = function() {};
With an explicitly exported interface:
window['MyLib'] = { 'method', method };
Generally, advanced mode only makes sense for a library if it has a small external interface relative to the amount of internal code. However, I definitely would encourage writing your library so that it can be consumed by an advanced mode compiled project (this requires separating out the export used when it is used as a stand-alone library, if they library itself is minified using advanced mode).
Objects in JavaScript can be used as Hashtable
(the key must be String)
Is it perform well as Hashtable the data structure?
I mean , does it implemented as Hashtable behind the scene?
Update: (1) I changed HashMap to hashtable (2) I guess most of the browser implement it the same, if not why not? is there any requirement how to implement it in the ECMAScript specs?
Update 2 : I understand, I just wonder how V8 and the Firefox JS VM implements the Object.properties getters/setters?
V8 doesn't implement Object properties access as hashtable, it actually implement it in a better way (performance wise)
So how does it work? "V8 does not use dynamic lookup to access properties. Instead, V8 dynamically creates hidden classes behind the scenes" - that make the access to properties almost as fast as accessing properties of C++ objects.
Why? because in fixed class each property can be found on a specific fixed offset location..
So in general accessing property of an object in V8 is faster than Hashtable..
I'm not sure how it works on other VMs
More info can be found here: https://v8.dev/blog/fast-properties
You can also read more regarding Hashtable in JS here:(my blog) http://simplenotions.wordpress.com/2011/07/05/javascript-hashtable/
"I guess most of the browser implement it the same, if not why not? is there any requirement how to implement it in the ECMAScript specs?"
I am no expert, but I can't think of any reason why a language spec would detail exactly how its features must be implemented internally. Such a constraint would have absolutely no purpose, since it does not impact the functioning of the language in any way other than performance.
In fact, this is absolutely correct, and is in fact the implementation-independence of the ECMA-262 spec is specifically described in section 8.6.2 of the spec:
"The descriptions in these tables indicate their behaviour for native
ECMAScript objects, unless stated otherwise in this document for particular kinds of native ECMAScript objects. Host objects may support these internal properties with any implementation-dependent behaviour as long as it is consistent with the specific host object restrictions stated in this document"
"Host objects may implement these internal methods in any manner unless specified otherwise;"
The word "hash" appears nowhere in the entire ECMA-262 specification.
(original, continued)
The implementations of JavaScript in, say, Internet Explorer 6.0 and Google Chrome's V8 have almost nothing in common, but (more or less) both conform to the same spec.
If you want to know how a specific JavaScript interpreter does something, you should research that engine specifically.
Hashtables are an efficient way to create cross references. They are not the only way. Some engines may optimize the storage for small sets (for which the overhead of a hashtable may be less efficient) for example.
At the end of the day, all you need to know is, they work. There may be faster ways to create lookup tables of large sets, using ajax, or even in memory. For example see the interesting discussion on this post from John Reseig's blog about using a trie data structure.
But that's neither here nor there. Your choice of whether to use this, or native JS objects, should not be driven by information about how JS implements objects. It should be driven only by performance comparison: how does each method scale. This is information you will get by doing performance tests, not by just knowing something about the JS engine implementation.
Most modern JS engines use pretty similar technique to speed up the object property access. The technique is based on so called hidden classes, or shapes. It's important to understand how this optimization works to write efficient JS code.
JS object looks like a dictionary, so why not use one to store the properties? Hash table has O(1) access complexity, it looks like a good solution. Actually, first JS engines have implemented objects this way. But in static typed languages, like C++ or Java a class instance property access is lightning fast. In such languages a class instance is just a segment of memory, end every property has its own constant offset, so to get the property value we just need to take the instance pointer and add the offset to it. In other words, in compile time an expression like this point.x is just replaced by its address in memory.
May be we can implement some similar technique in JS? But how? Let's look at a simple JS function:
function getX(point) {
return point.x;
}
How to get the point.x value? The first problem here is that we don't have a class (or shape) which describes the point. But we can calculate one, that is what modern JS engines do. Most of JS objects at runtime have a shape which is bound to the object. The shape describes properties of the object and where these properties values are stored. It's very similar to how a class definition describes the class in C++ or Java. It's a pretty big question, how the Shape of an object is calculated, I won't describe it here. I recommend this article which contains a great explanation of the shapes in general, and this post which explains how the things are implemented in V8. The most important thing you should know about the shapes is that all objects with the same properties which are added in the same order will have the same shape. There are few exceptions, for example if an object has a lot of properties which are frequently changed, or if you delete some of the object properties using delete operator, the object will be switched into dictionary mode and won't have a shape.
Now, let's imagine that the point object has an array of property values, and we have a shape attached to it, which describes where the x value in this property array is stored. But there is another problem - we can pass any object to the function, it's not even necessary that the object has the x property. This problem is solved by the technique called Inline caching. It's pretty simple, when getX() is executed the first time, it remembers the shape of the point and the result of the x lookup. When the function is called second time, it compares the shape of the point with the previous one. If the shape matches no lookup is required, we can take the previous lookup result.
The primary takeaway is that all objects which describe the same thing should have the same shape, i.e. they should have the same set of properties which are added in the same order. It also explains why it's better to always initialize object properties, even if they are undefined by default, here is a great explanation of the problem.
Relative resources:
JavaScript engine fundamentals: Shapes and Inline Caches and a YouTube video
A tour of V8: object representation
Fast properties in V8
JavaScript Engines Hidden Classes (and Why You Should Keep Them in Mind)
Should I put default values of attributes on the prototype to save space?
this article explains how they are implemented in V8, the engine used by Node.js and most versions of Google Chrome
https://v8.dev/blog/fast-properties
apparently the "tactic" can change over time, depending on the number of properties, going from an array of named values to a dictionary.
v8 also takes the type into account, a number or string will not be treated in the same way as an object (or function, a type of object)
if i understand this correctly a property access frequently, for example in a loop, will be cached.
v8 optimises code on the fly by observing what its actually doing, and how often
v8 will identify the objects with the same set of named properties, added in the same order (like a class constructor would do, or a repetitive bit of JSON, and handle them in the same way.
see the article for more details, then apply at google for a job :)