If I use an Assignment within conditional, for e.g.
if(userType='admin')
Flex throws a warning,unlike Java, which throws an error.
Why should Flex be doing this, despite being one of the newest languages?
1100: Assignment within conditional. Did you mean == instead of =?
Because assignments have a value in Actionscript, which makes that syntax legal, and they don't have a value in Java, which makes it not. The difference comes because despite recent Java-izations, Actionscript is descended from ECMAScript. Other consequences of this design are the ability to make statements like this:
var foo:Number = 0;
var bar:Number = 0;
foo = bar = 2;
assertEquals(2, foo);
assertEquals(2, bar);
IMO, this is the best behavior it could have - it doesn't break compatibility with older versions of Actionscript, and it doesn't remove language functionality for the purpose of handholding, but it does bring a common error to the attention of the user.
My guess is that the compiler probably automatically fixes it?
It is interesting though that Flex would do that.
(and btw, it's not "Flex", it's Actionscript 3)
Related
The definition of first-class citizen found in the wiki article says:
An object is first-class when it
can be stored in variables and data structures
can be passed as a parameter to a subroutine
can be returned as the result of a subroutine
can be constructed at run-time
has intrinsic identity (independent of any given name)
Can someone please explain/elaborate on the 5th requirement (in bold)? I feel that the article should have provided more details as in what sense "intrinsic identity" is capturing.
Perhaps we could use functions in Javascript and functions in C in our discussion to illustrate the 5th bullet.
I believe functions in C are second-class, whereas functions are first-class in Javascript because we can do something like the following in Javascript:
var foo = function () { console.log("Hello world"); };
, which is not permitted in C.
Again, my question is really on the 5th bullet (requirement).
Intrinsic identity is pretty simple, conceptually. If a thing has it, its identity does not depend on something external to that thing. It can be aliased, referenced, renamed, what-have-you, but it still maintains whatever that "identity" is. People (most of them, anyway) have intrinsic identity. You are you, no matter what your name is, or where you live, or what physical transformations you may have suffered in life.
An electron, on the other hand, has no intrinsic identity. Perhaps introducing quantum mechanics here just confuses the issue, but I think it's a really fantastic example. There's no way to "tag" or "label" an electron such that we could tell the difference between it and a neighbor. If you replace one electron with another, there is absolutely no way to distinguish the old one from the new one.
Back to computers: an example of "intrinsic identity" might be the value returned by Object#hashCode() in Java, or whatever mechanism a JavaScript engine uses that permits this statement to be false:
{} === {} // false
but this to be true:
function foo () {}
var bar = foo;
var baz = bar;
baz === foo; // true
So I was having a debate with a fellow engineer about looping in JavaScript. The issue was about the native for loop construct and prototype's each() method. Now I know there are lots of docs/blogs about for and for-each, but this debate is somewhat different and I would like to hear what some of you think.
Let's take the following loop for example
example 1
var someArray = [blah, blah, blah,...,N];
var length = someArray.length;
for(var index = 0; index < length; index++){
var value = someFunction(someArray[index]);
var someOtherValue = someComplicatedFunction(value, someArray[index]);
//do something interesting...
}
To me, this comes second nature mainly because I learnt how to code in C and it has carried me through. Now, I use the For-each in both C# and Java (bear with me, I know we are talking about JavaScript here..) but whenever i hear for loops, i think of this guy first. Now lets look at the same example written using Prototype's each()
example 2
var someArray = [blah, blah, blah,…..,N];
someArray.each(function(object){
var value = someFunction(object);
var someOtherValue = someComplicatedFunction(value, object);
//do something interesting...
});
In this example, right off the bat, we can see that the construct has less code, however, i think each time we loop through an object, we have to create a new function to deal with the operation in question. Thus this would preform badly with collections with large number of objects. So my buddy's argument was that example 2 is much easier to understand and is actually cleaner than example 1 due to its functional approach. My argument is that any programmer should be able to understand example 1 since it is taught in programming 101. So the easier argument doesn't apply and example 1 performs better than example 2. Then why bother with #2. Now after reading around i found out that when the array size is small the overhead for example 2 is minuscule. However people kept on talking about the lines of code you write is less and that example 1 is error prone. I still don't buy those reasons, so I wanted to know what you guys think…
You are not creating a new function on each iteration in the second example. There is only one function that keeps getting called over and over. To clarify the point of only a single function being used, consider how would you implement the each method yourselves.
Array.prototype.each = function(fn) {
for(var i = 0; i < this.length; i++) {
// if "this" should refer to the current object, then
// use call or apply on the fn object
fn(this[i]);
}
}
// prints each value (no new function is being created anywhere)
[1, 2, 3].each(function(v) { console.log(v); });
Sure, there is the overhead of calling a function in the first place, but unless you are dealing with massive collections, this is a non-issue in modern browsers.
Personally I prefer the second approach for the simple reason that it frees me from worrying about unnecessary details that I shouldn't be concerned about in the first place. Say if we are looping through a collection of employee objects, then index is just an implementation detail and in most cases, if not all, can be abstracted away from the programmer by constructs such as the each method in Prototype, which by the way is now a standard in JavaScript as it has been incorporated into ECMAScript 5th ed under the name forEach.
var people = [ .. ];
for(var i /* 1 */ = 0; i /* 2 */ < people.length; i++ /* 3 */) {
people[i /* 4 */].updateRecords();
people[i /* 5 */].increaseSalary();
}
Marked all 5 occurrences all i inline with comments. We could have so easily eliminated the index i altogether.
people.forEach(function(person) {
person.updateRecords();
person.increaseSalary();
});
For me the benefit is not in lesser lines of code, but removing needless details from code. This is the same reason why most programmers jumped on the iterator in Java when it was available, and later on the enhanced for loop when it came out. The argument that the same grounds don't hold for JavaScript just doesn't apply.
I'm fairly certain it does not create a new code function for every iteration, but rather calls the function on each one. It may involve a little more overhead to keep track of the iterator internally, (some languages allow the list to be changed, some don't) but it shouldn't be all that very much different internally than the procedural version.
But anytime you ask which is faster, you should ask, does it really matter? Have you put a code profiler on it and tested it with real world data? You can spend a lot of time figuring out which is faster, but if it only accounts for .0001% of your execution time, who cares? Use profiling tools to find the bottlenecks that really matter, and use whichever iteration method you and your team agree is easier to use and read.
Example one is not only error prone, for arrays of trivial length it's a poor choice - and the each (or forEach, as defined in JavaScript 1.6, yet IE8 still does not support it) is definitely style-wise the better choice.
The reason for this is simple: you are telling the code what to do, not how to do it. In my tests with firefox, the forEach method is about 30% the speed as a for loop. But when you're doing miniscule arrays it doesn't even matter that much. Much better to make your code cleaner and easier to understand (remember: what it's doing instead of how to do it), for not only your sanity the next time you come back to it, but for the sanity of anyone else looking at your code.
If the only reason you're including prototype is for the .each method, you're doing it wrong. If all you want is a clean iteration method, use the .forEach method - but remember to define your own. This is from the MDC page on forEach - a useful check to give yourself a .forEach method if none exists:
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp*/)
{
var len = this.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
fun.call(thisp, this[i], i, this);
}
};
}
You can tell from how this works, that a new function is not created for each item, though it is invoked for each item.
The answer is - its subjective.
For me, example 2 is not really THAT much less code, and also involves downloading (bandwidth) AND parsing/executing (execution-time) a ~30kb library before you can even use it - so not only is the method itself less efficient in and of itself, it also involves setup overhead. For me - arguing that example 2 is better is insanity - however that's just an opinion, many would (and are perfectly entitled to) disagree completely.
IMO the second approach is succinct and easier to use, though it gets complicated (see prototype doc) if you want to use things like break or continue. See the each documentation.
So if you are using simple iteration, use of the each() function is better IMO as it could be more succinct and easy to understand, although its less performant than the raw for loop
I have couple of questions about AS3 variables handling by AVM/compiler/scope
.1. This code in Flash will throw an error:
function myFunction() {
var mc:MovieClip=new MovieClip();
var mc:MovieClip=new MovieClip();
}
but it won`t throw an error in Flex (only warning in Editor). Why?
.2. How Flash sees variables in loops? Apparently this:
for (var i:int=0; i<2; i++) {
var mc:MovieClip=new MovieClip();
}
isn`t equal to just: var mc:MovieClip=new MovieClip();
var mc:MovieClip=new MovieClip(); because it will throw an error again as earlier in Flash, but in Flex in function not? Is Flash changing somehow my loop before compilation?
.3. Where in a class in equivalent to timeline in Flash - where in class I would put code which I put normally on timeline (I assume it is not constructor because of what I have written earlier, or maybe it`s a matter of Flash/Flex compiler)?
#fenomas thanks for explaining, but I checked 1. answer and it is not enitirely true :) this code: function myFunction() {
var mc:MovieClip=new MovieClip();
mc.graphics.beginFill(0x0000FF);
mc.graphics.drawRect(0,0,100,100);
mc.graphics.endFill();
addChild(mc);
var mc:MovieClip=new MovieClip();
mc.graphics.beginFill(0x000000);
mc.graphics.drawRect(0,0,30,30);
mc.graphics.endFill();
addChild(mc);
}
myFunction();
will compile in Flash in strict mode but with warning mode turned off and won`t throw an error during compile or runtime.
And it will also compile and execute nicely in Flex (event with -strict -warnings compiler commands) (checked with Flash CS3 and FlashBuilder 4).
The same code, but not wrapped in function will generate compile time error regardless off any error modes turned on (strict/warning)in Flash.
Is that what #back2dos said about Flash Compiler that behaves weirdly?
What is the differences between these two compilers Flash/Flex (why I have to change errors mode in Flash while Flex does not care about anything:) )?
Well, I will explain to you, how package level ActionScript (classes and global functions) is scoping.
The var statement declares a variable within the scope of the function body it is in. It's visibility is within the whole body. thus the following is completely valid.
a = 3;
if (Math.random()>0.5) {
var a:int = 0;
}
else {
a = 6;
}
this is horrible, but it's based on the abandonend ECMA-Script draft AS3 is based on ... yay! :(
for simplicity, imagine that all variable declarations are actually at the start of the containing function body (while their initialisation is actually performed in the place where you put it)
thus
for (var i:int=0; i<2; i++) {
var mc:MovieClip=new MovieClip();
}
is equal to
var i:int, mc:MovieClip;
for (i=0; i<2; i++) {
mc=new MovieClip();
}
the first piece of code from your first question to a duplicate variable defininition, which causes a compiler warning, but works as if you had made only one declaration.
as for your third question: there is no equivalent at all.
AS3 in the flash IDE and many designer friendly concepts (such as frames) are highly ambiguous. from a developer's point of view the flash IDE is about the worst piece of cr*p you can get for money (which stop it from being a great tool for design, drawing and animation). if you want clear and consistent behaviour, I advise you not to use the flash IDE for compiling ActionScript or to waste time on trying to find out why it behaves so weirdly. Apart from its quirks, it takes a long time to compile and the strange things it does to your ActionScript (such as converting local variable declaration to instance field declaration (which is probably the source of your problem)).
These are great questions. In order:
By default, Flash Authoring FLAs start in strict mode. You can change it in File > Publish Settings > AS3 settings. However, duplicate variable definitions are not a runtime error, just something that the authoring environment may or may not throw a warning or error about, depending on configuration and whether it's a class or frame script.
Incidentally, when comparing Flash and Flex make sure that your Flash scripts are inside a class, since frame scripts are a subtle different animal (as discussed below).
AS3 does not have block-level scope, so it implements a practice called "hoisting", where the compiler moves all declarations (but not assignments) to the beginning of the function in which they occur. Hence, even though your var statement is inside a loop, declaration occurs only once when the function begins to execute. See here for more details.
Frame scripts are a bit anomalous. They're sort of like anonymous functions, except that all scripts on a given timeline are considered to be in the same lexical scope. So if you use a var statement to create a local variable in one frame script, the variable will still exist when you execute a different frame script of the same object.
This is basically for historical reasons, but the result is essentially the same as having all your frame scripts in one big function and jumping around with GOTOs. Hence you should always keep all your real code in classes, and use frame scripts only to call class methods that you need to be synchronized with timeline animations. This not only lets you avoid needing to understand precisely how frame scripts differ from class code, it's good coding practice for a couple of reasons unrelated to the stuff we're talking about here.
I am new to using the Flex Compiler with FD, although certainly not new to flash/as3 and FD. Currently, i have been compiling my applications with FD/CS3 and want to make the switch to the flex compiler. One of the main things i want to experiment with the flex compiler is using Macros in AS3. For instance, say i have some extremely expensive operation that i wish to carry out:
private function Main():void
{
extremelyExpensiveOperation(params);
}
but i want to avoid the cost of a function lookup. So instead of using a function lookup I do something like
private function Main():void
{
<macro expandExtremelyExpensiveOperationHere(params)/>
}
obviously the syntax doesn't have to look exactly like that, but the macro gets expanded before compilation thus avoiding function lookup. Can anyone point me in the right direction?
use misch's preprocessor ... it supports macros as well ...
greetz
back2dos
In Flex 3,
var anInstance : MyClass = new MyClass();
with (anInstance)
{
property1 = "fred";
property2 = 5;
propert3 = 7;
}
does NOT flag "propert" as a non-existent property name. I thought this was a remainder of the evil JavaScript object behavior (referring to a property name of an object implicitly creates it), but it seems to be a side-effect of the "with".
This makes me very sad as the "with" was a little reminder of Delphi (except it works correctly there).
Am I missing something here?
From reading the documentation:
Actionscript apparently bubbles out for scope resolution on embedded variables (not surprising, since the syntax doesn't require an explicit dereference symbol like "." or "->" to indicate which variable names should be "withed".) So you effectively are creating a variable at global scope named propert3.
EDIT after thinking about why this "problem" exists -
Javascript is the epitome of non-strict typing. And Actionscript, being a strict superset of Javascript, can't enforce strict typing except as declared by its own extensions to the language - which means it must support untyped variables.
Some classes are dynamic (e.g. movieclip) and can have properties added to them at runtime:
http://flexblog.faratasystems.com/?p=95